从 lisp 中的套接字流读取行

Read-line from socket-stream in lisp

我正在 lisp 中的 TCP 客户端上工作,但在 reading/printing 套接字流正确时遇到困难。当客户端向服务器发送数据时,它应该会收到响应,我需要将其写入标准输出。这工作正常,除了我遇到响应打印两次的问题。如果我有多个命令被发送,只有最后一个会被打印两次。这是我的代码:

(defun socket-print (string socket)
    (write-line string (usocket:socket-stream socket))
    (force-output (usocket:socket-stream socket)))


(defun socket-read (socket)
    (write-line (read-line (usocket:socket-stream socket) nil)))


(defun mytest (command)
    (let ((socket (usocket:socket-connect _IP_ _PORT_)))
        (socket-print command socket)
        (socket-read socket)))

我不认为它打印了两次。我认为是 printing (via write-line) 一次,然后 write-linereturning 行,REPL 正在打印 return 值。例如,如果您将 mytest 修改为 return nil,我想您会看到您期望的输出:

(defun mytest (command)
    (let ((socket (usocket:socket-connect _IP_ _PORT_)))
        (socket-print command socket)
        (socket-read socket)
        nil))

这应该打印带有write-line的行,然后return nil,REPL 将打印 nil。将此与以下内容进行比较:

CL-USER> (defun echo (line)
           (write-line line))
ECHO
CL-USER> (echo "hello")
hello
"hello"
CL-USER> (progn
           (echo "hello")
           (echo "world"))
hello
world
"world"
CL-USER> (progn
           (echo "hello")
           (echo "world")
           nil)
hello
world
NIL
CL-USER> (progn
           (echo "hello")
           (echo "world")
           (values))
hello
world
; No value

另见:

  • How can I avoid the nil printed in the end?
  • prevent terminal output in LISP
  • When you type "hello, world" in Clojure REPL, why does it say 'nil'?(不是 Common Lisp,但概念相同)