gpt4 book ai didi

java - BufferedReader 在 readLine() 上阻塞

转载 作者:搜寻专家 更新时间:2023-11-01 01:31:29 25 4
gpt4 key购买 nike

出于某种原因,我无法从服务器上的客户端读取行。客户端能够毫无问题地发送线路,但服务器不会移动到第一次调用 clientIn.readLine() 之后。我认为它正在阻塞,但我不知道如何处理它。

当我在没有服务器端循环的情况下发送行时也会发生这种情况。

客户端.java

public void run()
{
try {
socket = new Socket(ip, port);
System.out.println("Client connected on port: " + socket.getRemoteSocketAddress());
//wrap streams for ease
BufferedReader serverIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter serverOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
System.out.println("starting messages");

//send messages
serverOut.println("hello from: " + socket.getLocalSocketAddress());
serverOut.println("msg1: " + this.hashCode());
serverOut.println("msg2: final test");
//close the connection
socket.close();

} catch (IOException e) {
e.printStackTrace();
}
}

服务器.java:

public void run()
{
System.out.println("Server Running on port: " + serverSocket.getLocalPort());
while(true)
{
try {
//listen for connections
Socket client = serverSocket.accept();

//record sockets
connections.put(client.getRemoteSocketAddress(), client);

//wrap streams for ease
BufferedReader clientIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter clientOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())));

//send messages
String line = null;
while((line = clientIn.readLine()) != null)
{
System.out.println(line);
}

//ends the connection
client.close();
System.out.println("Client disconnected");
} catch (IOException e) {
e.printStackTrace();
}
}
}

最佳答案

socket.close();

您正在关闭您应该关闭 PrintWriter 的套接字:

serverOut.close();

当您从下方关闭套接字时,您将丢失 PrintWriter 中的缓冲数据。

关于java - BufferedReader 在 readLine() 上阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49870416/

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