我对网络这个程序感到困惑。我应该创建一个猜测服务器,在5150创建一个套接字并等待客户端。我的服务器不应该与任何数量的顺序客户端一起玩游戏并持续运行,直到客户端连接并发送" SHUT DOWN"作为它的初始信息。它应该实现二进制搜索程序,其中客户端向它发送两个数字,表示列表的下边界和上边界。我的服务器应该以猜测回复,然后如果数字高,低,赢或丢失,它会从客户端收到消息。显然当游戏结束时客户端和服务器端之间的连接。 这是我的代码到目前为止,我正在努力争取甚至出错!任何有用的帮助或例子都会非常感激!
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) {
}
}
答案 0 :(得分:0)
这是我将如何做到的。
为您的游戏服务器创建一个实现Runnable的类,例如
class GameThread implements Runnable {
public void run() {
// Game logic here.
// Read user input
// If a user guesses the right number, call shutdown on GuessingGame class
}
你的游戏服务器程序创建线程,例如
class GuessingGame {
public static void main(String[] args)
{
while(true) {
// Accept connections
}
// create threads
}
void shutDown() {
// Cleanup
// Terminate threads
// Close connections
System.exit(1);
}
}
这允许多个连接到您的游戏服务器