0
我对这个程序与网络感到困惑。我应该创建一个猜测服务器,它在5150处创建一个套接字并等待客户端。我的服务器不应该与任何数量的顺序客户端一起玩游戏,并且持续运行,直到客户端连接并发送“关闭”作为其初始消息。它应该实现二进制搜索程序,客户端向其发送两个数字,表示列表的上下边界。我的服务器应该回复一个猜测,然后从客户端收到一条消息,说明数字是高,低,赢,还是输掉了游戏。很明显,当游戏结束时,客户端和服务器之间的连接就结束了。 这是我的代码到目前为止,我正在努力解决什么是错误的核心!任何帮助如此以往或例子将不胜感激!java中的二进制搜索猜谜游戏服务器端
public class GuessingServer {
public static void main(String[] args){
String inputLine = "";
int num1 = 0;
int num2 = 0;
int guess = 0;
String response = "";
try {
//set up server
ServerSocket serverSocket = new ServerSocket(5150);
//accept the client (socket)
Socket clientSocket = serverSocket.accept();
//try to creates scanner and print writer
Scanner scan = new Scanner(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter print = new PrintWriter(clientSocket.getOutputStream(), true);
//do game stuff:
while(scan.nextLine()!= null){
if(inputLine.equals("SHUT DOWN")){
//shuts down the server
serverSocket.close();
}
//scanner to read the line:
inputLine = scan.nextLine();
Scanner line = new Scanner(inputLine);
if(response != ""){
while(line.hasNext() == true){ //while the scanner line has something next in it
//get the numbers
num1 = line.nextInt();
num2 = line.nextInt();
//decide and send guess to client:
guess = (((num2 - num1)/2)+num1);
print.println(guess);
System.out.println(guess);
}
}else if (response.equals("high") || response.equals("low")){
while(line.hasNext() == true){ //while the scanner line has something next in it
//get the numbers
num1 = line.nextInt();
num2 = line.nextInt();
//-->decide and send guess to client:
guess = (((num2 - num1)/2)+num1);
print.println(guess);
System.out.println(guess);
}
}
else if(response.equals("won") || response.equals("lost")){
//game is over:
scan.close();
line.close();
clientSocket.close();
}
scan.close();
line.close();
clientSocket.close();
serverSocket.close();
}
} catch (IOException e) {
}
}
“连续客户”你这是什么意思?如果多个用户可以同时玩,那么通常你需要Runnable类,并为每个玩家产生一个线程 – Norsk
我真的不知道它到底是什么意思,但我不认为我们需要我们只编写服务器端为我的实验室,并使用此程序的junit测试文件 – Tiff
我的答案进一步下降可能会帮助你。我做了一个类似的事情,当我做了一个网络编程课程 – Norsk