[英]java socket can't send message using BufferedWriter
I am trying to use BufferedWriter
to send a message to the server from the client or server to client. 我正在尝试使用
BufferedWriter
从客户端或服务器到客户端向服务器发送消息。 However nothing will send, but it will listen if you send a message to it. 但是什么也不会发送,但是如果您向它发送消息,它将监听。 I am not sure what I am doing wrong but I think the problem is from here.
我不确定自己在做什么错,但我认为问题出在这里。
ActionListener buttonActive= new ActionListener(){
public void actionPerformed(ActionEvent e) {
messageTextArea.append(textMessage.getText()+ "\n");
sendText = textMessage.getText();
}
};
sendButton.addActionListener(buttonActive);
private void startSending(){
SwingWorker <Void, Void> sendingThread = new SwingWorker <Void, Void>(){
protected Void doInBackground() throws Exception {
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
while(connected){
writer.write(sendText);
writer.flush();
}
return null;
}
};
sendingThread.execute();
}
@trashgod and @madProgrammer gave me a solution using printWriter which works but I want me to make a few more version using BufferedWriter
+ BufferedReader
, OutputStream+ InputStream
and BufferedWriter
+ PrintWriter
, however i want to make the BufferedWriter
+ BufferedReader
. @trashgod和@madProgrammer给我提供了一个使用printWriter的解决方案,该解决方案可以工作,但我希望我使用
BufferedWriter
+ BufferedReader
, OutputStream+ InputStream
和BufferedWriter
+ PrintWriter
制作更多版本,但是我想制作BufferedWriter
+ BufferedReader
。
Your code does indeed send data. 您的代码确实确实在发送数据。 Maybe the client is calling
readLine()
? 客户端可能正在调用
readLine()
吗? As you aren't sending a line terminator, it will block forever. 由于您不发送行终止符,因此它将永远阻塞。
But your code doesn't make much sense. 但是您的代码没有多大意义。 Writing the same text in a loop can't be what you intended.
在循环中编写相同的文本并不是您想要的。 And there is no such thing as a
PrintReader
. 而且没有
PrintReader
这样的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.