我看到了与我类似的问题,但我仍然无法解决这个问题。我正在尝试进行中继聊天。我已经完成了所有的冲洗。我甚至尝试过autoflush(使用println)。但是在我发送给服务器的第一条消息之后,不再发送成功的消息。我没有关闭版画。我检查了套接字,是的,它仍然连接,我打印了要发送的消息,似乎没有任何错误。非常感谢帮助。
这是客户端代码的一部分:
public void initializeConnection(){
try {
host = InetAddress.getLocalHost();
clientSocket = new Socket(host.getHostAddress(), port);
outToServer = new PrintWriter(clientSocket.getOutputStream(),true);
String message = outMsgArea.getText()+"Hello";
outToServer.println(message);
System.out.println(clientSocket.isConnected());
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==quit){
try {
outToServer.close();
clientSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
else if(e.getSource()==button){
if(outMsgArea.getText()!=null || !outMsgArea.getText().equals("")){
/*try {
outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
String message = outMsgArea.getText()+"Hello";
System.out.println(clientSocket.isConnected());
outToServer.println(message);
outToServer.flush();
//outToServer.println(message);
outMsgArea.setText("");
}
}
}
服务器:
while(true) {
try {
Socket connectionSocket = servSocket.accept();
Scanner inFromClient = new Scanner(connectionSocket.getInputStream());
String clientSentence = inFromClient.nextLine();
System.out.println(clientSentence);
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
}
答案 0 :(得分:2)
我不认为
Socket connectionSocket = servSocket.accept();
Scanner inFromClient = new Scanner(connectionSocket.getInputStream());
应该在while循环中。