3

usocketおよび、force-outputについて質問させてください。

usocketの勉強のために簡単なEchoサーバを作りました。 echo1とecho2です。 echo1に対してtelnetでの接続を試みたところ、正常に動作いたしました。 しかしecho2に対してtelnet接続を試みたところ、文字列をサーバに送信したにも関わらず、サーバからレスポンスが戻ってきませんでした。

(defun echo1 (host port)
  (usocket:with-socket-listener (socket host port)
    (do () (nil nil)
      (usocket:with-server-socket (socket (usocket:socket-accept socket :element-type '(unsigned-byte 8)))
        (let ((stream (usocket:socket-stream socket)))
          (do ((byte (read-byte stream nil)
                     (read-byte stream nil)))
              ((null byte) nil)
            (write-byte byte stream)
            (force-output stream)))))))



(defun echo2 (host port)
  (usocket:with-socket-listener (socket host port)
    (do () (nil nil)
      (usocket:with-server-socket (socket (usocket:socket-accept socket :element-type '(unsigned-byte 8)))
        (let ((stream (usocket:socket-stream socket)))
          (do ((byte (read-byte stream nil)
                     (read-byte stream nil)))
              ((null byte) nil)
            (write-byte byte stream))
          (force-output stream))))))

echo1とecho2の違いは、むろん、force-outputの位置です。 そこで、伺いたのですが、どうしてforce-outputの位置の違いによって、このような違いが生まれるのでしょうか。なお、当方の使用処理系はSBCLです。

1 件の回答 1

4

force-output が実行されるまで入力データがバッファリングされるためです。

USOCKET API documentation

force the output to be written to the network?

When you write output to the stream, it may be buffered before sent over the network - for optimal performance of small writes. You can force the buffer to be flushed the same way as with normal streams:

(format (socket-stream socket) "Hello there~%")   ;; output into buffers
(force-output (socket-stream socket))             ;; <== flush the buffers, if any

echo1 では1行ごとにクライアント側のソケットへ送られますが、echo2 では EOF が入力されるまでバッファリングされる(クライアント側へは送られない)ことになります。

3
  • ご解答、ありがとうございます。 少し確認させていただきたいのですが、EOFというのは、この場合、クライアントとの通信が切断された時と、解釈してもよいのでしょうか。 echo2の場合、write-byteで書き込まれたデータ(すなわち変数byte)は、その時には送信されず、バッファに蓄えられる。そして通信が切断されたのち、force-outputによって、それまでにバッファに蓄えられた情報がクライアントに送信される。しかし、その時には既に通信は切断されているため、結果として、クライアントに情報が送信されないことになる。そのような理解で大丈夫でしょうか。
    – Rio
    2015年1月1日 15:38
  • はい、その通りです。ご存知かと思いますが、「(read-byte stream nil :eof)」「((eq byte :eof) nil)」と書いておいた方が可読性が高いのかもしれませんね。
    – user4986
    2015年1月1日 19:04
  • ありがとうございました。助かりました。 理解出来たと思います。
    – Rio
    2015年1月1日 22:35

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。