[英]Server accept socket but after that the socket cannot receive anything
I've encountered a very strange problem (since this always worked before) when building a client-server chat program. 在构建客户端 - 服务器聊天程序时,我遇到了一个非常奇怪的问题(因为这总是起作用)。
The serversocket accepts without any problem the incoming connection of the client, but when I try to read from the socket's inputstream the whole method blocks and only releases when I close the client's socket. serversocket接受客户端的传入连接没有任何问题,但是当我尝试从套接字的输入流中读取时,整个方法阻塞并且仅在我关闭客户端套接字时释放。
I've even tried it with the sample code on docs.oracle.com, but the problem remains. 我甚至尝试使用docs.oracle.com上的示例代码,但问题仍然存在。
Can anybody point me out the error I'm obviously not seeing? 任何人都可以指出我显然没有看到的错误吗?
Server code: 服务器代码:
public class Server {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
System.out.println("Creating server socket");
ServerSocket internetSocket = new ServerSocket(60000);
if(!internetSocket.isClosed()) {
while(true) {
Socket s = internetSocket.accept();
System.out.println("accepted socket!");
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
}
Client code: 客户代码:
public class Client {
public static void main(String[] args) throws IOException {
Socket s = null;
try {
s = new Socket("localhost", 60000);
} catch (UnknownHostException ex) {
Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter outStream = new PrintWriter(s.getOutputStream());
for(int i=0; i<10; i++) {
outStream.println("test");
System.out.println("Sending the message \"test\"");
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex);
}
}
s.close();
}
}
You forgot to add a true as the 2nd parameter when creating the printwriter printwriter 在创建printwriter printwriter时,您忘记添加true作为第二个参数
new PrintWriter(s.getOutputStream(), true);
It will make it flush automatically. 它会自动冲洗。
the method readLine()
is waiting for \\n character to appear in the stream (the method blocks until it sees end line delimeter). 方法
readLine()
正在等待\\ n字符出现在流中(方法阻塞,直到它看到结束行分隔符)。
Try sending "test\\\\n"
from the client and see what happens. 尝试从客户端发送
"test\\\\n"
,看看会发生什么。
And remember to flush()
the output stream on the client side 并记住在客户端
flush()
输出流
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.