猜数字游戏
游戏的规则如下:
当客户端第一次连接到服务器端时,服务器端生产一个【0,50】之间的随机数字,然后客户端输入数字来猜该数字,每次客户端输入数字以后,发送给服务器端,服务器端判断该客户端发送的数字和随机数字的关系,并反馈比较结果,客户端总共有5次猜的机会,猜中时提示猜中,当输入”quit”时结束程序。
为了实现这个游戏,我写了三个类,客户端,服务器端以及一个实现多客户端的线程类。
该程序是以前学习 Java 网络编程时所写(写于2013年5月),还有很多地方有待完善,可以参考牛人的文章。
客户端类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class TCPGameClient
{
static BufferedReader br = null;
static Socket socket = null;
static InputStream is = null;
static OutputStream os = null;
final static String HOST = "localhost";
final static int PORT = 10008;
public final static String EQUALS = "E" ;
public final static String GREATER = "G";
public final static String LESSER = "L";
public final static String NEXT = "NEXT";
public static void main(String[] args) throws Exception
{
//初始化socket,输入输出流
init();
System.out.println("The Game Begain!");
byte[] bufResult = new byte[10];
while(true)
{
//获取server产生的随机数
String strDate = new String(receive());
System.out.println("Please enter your guess:(If you want to end,input quit)");
//从控制板获取输入字符
String str = br.readLine();
if(isQuit(str))
{
System.out.println("Bye!");
break;
}
//client端控制猜谜次数
int count = 5;
while(count > 0)
{
//向 server端发送client 猜的数字
send(str.getBytes());
//接收来自server的对比后的反馈
bufResult = receive();
String result = new String(bufResult);
if(EQUALS.equalsIgnoreCase(result))
{
System.out.println("Congratulations! You are rgiht.");
send(NEXT.getBytes());
break;
} else if(GREATER.equalsIgnoreCase(result))
{
count --;
System.out.println("Greater!");
System.out.println("You have " + count + " chances left.");
} else if(LESSER.equalsIgnoreCase(result))
{
count --;
System.out.println("Lesser!");
System.out.println("You have " + count + " chances left.");
} else{;}
//猜谜次数未到?继续
if(count > 0)
{
System.out.println("Please enter your guess:");
str = br.readLine();
}
//猜谜次数已到,还没猜出?打印谜底,同时告诉server开始下一轮猜谜游戏
if(count == 0)
{
System.out.println("The right answer is: " + strDate);
send(NEXT.getBytes());
}
}
}
close();
}
private static void init() throws IOException
{
br = new BufferedReader(new InputStreamReader(System.in));
socket = new Socket(HOST, PORT);
is = socket.getInputStream();
os = socket.getOutputStream();
}
private static byte[] receive() throws IOException
{
byte[] buf = new byte[10];
int len = is.read(buf);
byte[] receiveData = new byte[len];
System.arraycopy(buf, 0, receiveData, 0, len);
return receiveData;
}
private static void send(byte[] b) throws IOException
{
os.write(b);
}
private static boolean isQuit(String str)
{
boolean flag = false;
if(null == str)
flag = false;
else
{
if("quit".equalsIgnoreCase(str))
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
private static void close() throws Exception
{
socket.close();
is.close();
os.close();
}
}
服务器类
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPGameServer
{
static ServerSocket serverSocket = null;
final static int PORT = 10008;
public static void main(String[] args) throws IOException
{
try
{
//初始化ServerSocke,开始监听
serverSocket = new ServerSocket(PORT);
System.out.println("The Server started.");
while(true)
{
Socket socket = serverSocket.accept();
new TCPGameThread(socket).start();
}
}
catch (Exception e)
{
e.printStackTrace();
}
serverSocket.close();
}
}
线程类
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;
public class TCPGameThread extends Thread
{
Socket socket = null;
InputStream is = null;
OutputStream os = null;
public final static String EQUALS = "E" ;
public final static String GREATER = "G";
public final static String LESSER = "L";
public final static String NEXT = "NEXT";
public TCPGameThread(Socket socket) throws IOException
{
this.socket = socket;
is = this.socket.getInputStream();
os = this.socket.getOutputStream();
}
@Override
public void run()
{
try
{
while(true)
{
//产生一个在[0,50]之间的随机数
int randomData = -1;
randomData = createRandom(0, 50);
String str = String.valueOf(randomData);
System.out.println("random data: " + randomData);
try
{
//将该随机数发送给client端
send(str.getBytes());
}catch(Exception e){
break;
}
while(true)
{
try
{
//接收来自client端的猜数
byte[] b = receive();
String strReceive = new String(b, 0, b.length);
System.out.println("strReceive: " + strReceive);
if(isNext(strReceive))break;
//比较谜底和猜数之间的关系并反馈比较结果
String checkResult = checkClientData(randomData, strReceive);
send(checkResult.getBytes());
}
catch (IOException e)
{
break;
}
}
}
}
catch (Exception e)
{
try
{
close();
}
catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private byte[] receive() throws IOException
{
byte[] buf = new byte[10];
int len = is.read(buf);
byte[] receiveData = new byte[len];
System.arraycopy(buf, 0, receiveData, 0, len);
return receiveData;
}
private void send(byte[] b) throws IOException
{
os.write(b);
}
private int createRandom(int start, int end)
{
Random r = new Random();
return r.nextInt(end - start + 1) + start;
}
private String checkClientData(int randomData, String data)
{
String checkResult = null;
int buf = Integer.parseInt(data);
if(buf == randomData)
{checkResult = EQUALS;}
else if(buf > randomData)
{checkResult = GREATER;}
else if(buf < randomData)
{checkResult = LESSER;}
else
{;}
return checkResult ;
}
private void close() throws Exception
{
socket.close();
is.close();
os.close();
}
private static boolean isNext(String str)
{
boolean flag = false;
if(null == str)
flag = false;
else
{
if(NEXT.equalsIgnoreCase(str))
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
}