Writing to Socket outputStream w/o closing it

假装没事ソ 提交于 2019-12-06 04:44:43

问题


I'd like to write some messages to the server. Each time, for the tramsmitting only, I'm closing the outputStream and reopen it when I have to send the next message.

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

How Can I keep this Socket's OutputStream, os, open and still be able to send the message?

Thanks.


回答1:


I am missing something here. If you don't call close, it will not close. For example,

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();



回答2:


In most protocols, the server accepts som kind of EOF symbol. Send such a symbol instead of closing the stream.

For example, IRC servers interpret "\r\n" as the end of a message. This would 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( );

Also, you should wrap your outputStream with DataOutputStream. This wrapper creates more portable output. Plain OutputStream can cause trouble with certain primitive datatypes if server and client have different computer architectures.




回答3:


Wrap the Socket's OutputStream in a PrintWriter and call the PrintWriter's 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.



回答4:


I have found the problem and it lays on the client's side. On the client, I have used -

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

That means, the client waits till server's outputStream closed, and then processing the incoming data.



来源:https://stackoverflow.com/questions/2826311/writing-to-socket-outputstream-w-o-closing-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!