java 写入 Socket outputStream 而不关闭它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2826311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:01:27  来源:igfitidea点击:

Writing to Socket outputStream w/o closing it

javasocketsnetwork-programmingou

提问by eyal

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.

我想写一些消息到服务器。每次,仅对于传输,我都会关闭 outputStream 并在必须发送下一条消息时重新打开它。

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?

我怎样才能保持这个 Socket 的 OutputStream, os, 打开并且仍然能够发送消息?

Thanks.

谢谢。

采纳答案by ZZ Coder

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

我在这里遗漏了一些东西。如果你不调用close,它就不会关闭。例如,

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

回答by rompetroll

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

在大多数协议中,服务器接受某种 EOF 符号。发送这样的符号而不是关闭流。

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

例如,IRC 服务器将“\r\n”解释为消息的结尾。这将是一个打开的 OutputStream 上的 2 条消息:

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.

此外,您应该使用 DataOutputStream 包装您的 outputStream。这个包装器创建了更便携的输出。如果服务器和客户端具有不同的计算机体系结构,则普通 OutputStream 可能会导致某些原始数据类型出现问题。

回答by eyal

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.

这意味着,客户端等待服务器的 outputStream 关​​闭,然后处理传入的数据。

回答by Finbarr

Wrap the Socket's OutputStreamin a PrintWriterand call the PrintWriter's printlnmethod.

Socket's包裹OutputStream在 a 中PrintWriter并调用PrintWriter'sprintln方法。

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.