I am trying to use BufferedWriter to send a message to the server from the client or server to client. 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.
Your code does indeed send data. Maybe the client is calling
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.