我对我希望客户按顺序与服务器通信的方式感到困惑。例如,我正在创建一个多人tic tac toe游戏,其中2个客户端将连接到游戏服务器。然后客户轮流放入x的坐标。但是,当我在while循环中使用break
时,它只允许它们在断开套接字之前输入一次。我如何做到这样,客户端被暂时阻止而另一个客户端回答?
编辑:我不打算为此目的使用多线程。
服务器(为了阅读而截断):
try {
while (true) {
System.out.println("Awaiting connection!");
Socket clientSocket = server.accept();
System.out.println("Player " + noOfPlayers + " has connected!");
noOfPlayers ++;
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (!newGame.checkWinner()) {
out.println(newGame.currentPlayer());
input = in.readLine();
x = Integer.parseInt(input.split("\\,+")[0]);
y = Integer.parseInt(input.split("\\,+")[1]);
newGame.addPoint(x, y);
out.println("Moved");
if (newGame.checkWinner()) {
System.out.println("The winner is " + newGame.currentPlayer());
out.println("The winner is " + newGame.currentPlayer());
server.close();
break;
}
else if (newGame.boardFilledUp()) {
newGame.loadBoard();
out.println("It's a draw!");
server.close();
break;
}
newGame.loadBoard();
newGame.changePlayer();
break;
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
客户端(因阅读而被截断):
while (true) {
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
// Read input from server
BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
// Read input from client
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your coordinates in x,y form: ");
String userInput;
char serverOutput;
serverOutput = in.readLine().charAt(0);
System.out.println("Current player is " + serverOutput);
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("You sent: " + userInput);
}
break;
}
答案 0 :(得分:0)
找出问题所在。我没有刷新PrintWriter。