gpt4 book ai didi

Java Sockets - 服务器在客户端发送响应后挂起

转载 作者:行者123 更新时间:2023-12-02 07:17:14 24 4
gpt4 key购买 nike

只是想获取套接字的句柄。服务器和客户端运行在两个不同的程序中。

它们似乎彼此连接良好,但客户端无法正确地将其输出发送到服务器。服务器只是挂起。代码如下:

服务器:

  private ServerSocket serverSocket;
private Socket client;

public void run() throws Exception {
serverSocket = new ServerSocket(20005);
while(currentState == Game.State.NORMAL) {
client = serverSocket.accept();
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String clientInput = in.readLine();

// Takes the client input string and does some simple game logic that returns a Gson object
Gson serverResponse = processInput(clientInput);
out.write(serverResponse.toString());
out.flush();
}
}

客户:

Socket 客户端套接字;

  void run() throws Exception {
clientSocket = new Socket("192.168.0.24", 20005);
PrintWriter out;
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

// Print the state of the game - returns false if state is win or lose.
while(printState()) {
out = new PrintWriter(clientSocket.getOutputStream(), true);
// This method just takes some input from the console
String clientInput = getInput();

out.write(clientInput);
out.flush();

String serverResponse = in.readLine();

updateState(serverResponse);
}
}
}

正在发生一些潜在的游戏逻辑,但它非常小,应该是无关紧要的。我想我只是误解了一些基本的东西。

谢谢大家。

最佳答案

确保发送换行符以匹配 Server 中的 in.readLine() 语句。

out.write(clientInput + "\n");

服务器->客户端发送数据时也是如此。

关于Java Sockets - 服务器在客户端发送响应后挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14793539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com