在构建客户端-服务器聊天程序时,我遇到了一个非常奇怪的问题(因为以前总是这样)。
服务器套接字毫无问题地接受客户端的传入连接,但是当我尝试从套接字的输入流中读取时,整个方法会阻塞并且仅在我关闭客户端的套接字时才释放。
我什至用 docs.oracle.com 上的示例代码尝试过它,但问题仍然存在。
谁能指出我显然没有看到的错误?
服务器代码:
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);
}
}
}
}
}
客户端代码:
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();
}
}