4

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.

4

4 に答える 4

3

ここで何かが欠けています。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();
于 2010-05-13T11:40:53.250 に答える
2

ほとんどのプロトコルでは、サーバーは何らかの種類の EOF シンボルを受け入れます。ストリームを閉じる代わりに、そのようなシンボルを送信します。

たとえば、IRC サーバーは "\r\n" をメッセージの終わりとして解釈します。これは、開いている 1 つの OutputStream で 2 つのメッセージになります。

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

また、outputStream を DataOutputStream でラップする必要があります。このラッパーは、より移植性の高い出力を作成します。サーバーとクライアントのコンピューター アーキテクチャが異なる場合、プレーンな OutputStream は特定のプリミティブ データ型で問題を引き起こす可能性があります。

于 2010-05-13T12:01:13.970 に答える
1

私は問題を発見しましたが、それはクライアント側にあります。クライアントで、私は使用しました-

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

つまり、クライアントはサーバーの outputStream が閉じられるまで待機し、受信データを処理します。

于 2010-05-20T08:05:31.623 に答える
1

を でラップし、のSocketメソッドを呼び出します。OutputStreamPrintWriterPrintWriterprintln

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.
于 2010-05-13T11:35:52.027 に答える