usocket and force-output questions

Asked 2 years ago, Updated 2 years ago, 66 views

Let me ask you about usocket and force-output.

I made a simple Echo server to study usocket. It's echo1 and echo2. I tried telnet connection to echo1 and it worked fine. However, when I tried to telnet to echo2, I sent a string to the server, but the server didn't respond.

 (defunecho1 (host port)
  (usocket: with-socket-listener (socket host port)
    (do() (nil nil)
      (usocket: with-server-socket(usocket: socket-accept socket:element-type'(unsigned-byte8))))
        (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(usocket: socket-accept socket:element-type'(unsigned-byte8))))
        (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)))

The difference between echo1 and echo2 is, of course, the force-output position. So, I asked, why is this difference caused by the difference in the position of force-output?In addition, our processing system is SBCL.

common-lisp socket

2022-09-30 19:13

1 Answers

This is because input data is buffered until force-output is executed.

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 optimum 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 sends it to the client side socket line by line, but echo2 buffers it until EOF is entered (not sent to the client side).


2022-09-30 19:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.