我曾經見過類似的問題,但我仍然無法解決此問題。我正在嘗試進行中繼聊天。我做了所有的沖洗。我什至嘗試autoflush(與println)。但在發送給服務器的第一條消息之後,不會再發送成功的消息。我沒有關閉printwriter。我檢查了套接字,是的,它仍然連接,我打印了要發送的消息,似乎沒有錯。非常感謝幫助。PrintWriter僅發送第一條消息
這裏是客戶端代碼的一部分:
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();
}
}
}
你能分享你的代碼嗎? –
發佈一些代碼。 –
你也寫過服務器嗎?你可以在那裏發佈處理輸入的代碼嗎? – Kevin