Write to Socket outputStream without closing

I would like to write some messages to the server. Each time, only for trampling, I close the outputStream and open it again when I need to send the next message.

os.write(msgBytes); os.write("\r\n".getBytes()); os.flush(); os.close(); 

How can I save this Socket OutputStream, os, open and still be able to send a message?

Thanks.

+4
source share
4 answers

Something is missing for me. If you do not call closely, it will not be closed. For instance,

 os.write(msgBytes); os.write("\r\n".getBytes()); os.flush(); // Do something os.write("more message"); os.flush(); // When you are finally done os.close(); 
+3
source

In most protocols, the server accepts some EOF character. Send such a character instead of closing the stream.

For example, IRC servers interpret "\ r \ n" as the end of a message. This will be 2 messages on one open OutputStream:

 PrintStream printStream = new PrintStream(socket.getOutputStream()); printStream.print("JOIN #channel1\r\n"); printStream.flush( ); printStream.print("JOIN #channel2\r\n"); printStream.flush( ); 

In addition, you must wrap your outputStream with a DataOutputStream. This shell creates more portable output. Plain OutputStream can cause problems with some primitive data types if the server and client have different computer architectures.

+2
source

Wrap the Socket OutputStream in PrintWriter and call the PrintWriter println method.

 PrintWriter pw = new PrintWriter(socket.getOutputStream()); .... pw.println(message); // call repeatedly to send messages. .... pw.close(); // when finished writing to server and want to close conn. 
+1
source

I found the problem, and it lies on the client side. On the client, I used -

 count = inputStream.read(buffer)) > -1 

This means that the client waits until the outputStream server is closed, and then processes the incoming data.

+1
source

Source: https://habr.com/ru/post/1309655/


All Articles