gpt4 book ai didi

java - 我无法将响应发送回客户端

转载 作者:行者123 更新时间:2023-11-29 05:50:34 24 4
gpt4 key购买 nike

我正在创建一个服务器和一个客户端。现在我可以从 ClientServerThread 发送消息,并且 ServerThread 能够获取消息。但是当 ServerThread 尝试响应时,Client 没有收到响应,但消息已发送。它似乎在等待响应,但永远无法接收到响应。

服务器线程:

public class ServerThread extends Thread {
private Socket socket;
private DataOutputStream outToClient;
private BufferedReader inFromClient;

public ServerThread(Socket socket) {
try {
System.out.println("Thread started");
this.socket = socket;
outToClient = new DataOutputStream(socket.getOutputStream());
inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

public void run() {
System.out.println("Thread running");
try {
System.out.println("ServerThread: " + inFromClient.readLine());
outToClient.writeBytes("I Can help you");
} catch (Exception e) {
e.printStackTrace();
}
}
}

服务器:

public class Server {
public static final int PORT = 5589;

public static void main(String[] args) {
ServerSocket socket;

try {
socket = new ServerSocket(5589);

while (true)
new ServerThread(socket.accept()).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}

客户:

public class Client {
public static void main(String args[]) throws Exception {
Socket socket = new Socket("localhost", App.PORT);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter outToServer = new PrintWriter(socket.getOutputStream(), true);

outToServer.println("Hello, I'm Lost");

System.out.println(inFromServer.readLine()); //Hangs on this line

socket.close();
}
}

最佳答案

您的数据在服务器端缓冲,直到缓冲区已满才会自动发送:您应该在 .writeBytes() 之后在服务器端 .flush() > 以确保它被发送,即使您没有达到缓冲区大小(这取决于操作系统和套接字配置)。

关于java - 我无法将响应发送回客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14026679/

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