[英]BufferedReader Blocking on readLine()
For some reason I am not able to read lines from the client on the server. 由于某种原因,我无法从服务器上的客户端读取行。 The client is able to send lines without a problem but the server wont move past the first time clientIn.readLine() is called .
客户端能够毫无问题地发送行,但服务器不会在第一次调用clientIn.readLine()时移动。 I assume it is blocking but I don't know how to deal with it.
我认为它是阻止但我不知道如何处理它。
This also occurred when I sent lines without the server side loop. 当我发送没有服务器端循环的行时也会发生这种情况。
Client.java Client.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();
}
}
Server.java: Server.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();
You are closing the socket where you should be closing the PrintWriter
: 您正在关闭应该关闭
PrintWriter
的套接字:
serverOut.close();
You're losing buffered data in the PrintWriter
when you close the socket out from under it. 当你从它下面关闭套接字时,你正在丢失
PrintWriter
缓冲数据。
您需要flush()
您的serverOut
,否则您的消息将保留在BufferedWriter的缓冲区中,并且永远不会发送到服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.