0

我正在尝试使用 TCP/IP 套接字(在 Linux 系统中使用 sbcl 和 usocket 库)从 Lisp 脚本与另一个程序进行通信。

到目前为止,我得到了这段代码:

(require 'asdf)
(require 'usocket)

(defun start-client ()
    (   usocket:with-client-socket
    (socket stream "0.0.0.0" 30000)


    (loop for x in '("1~%" "2~%" "3~%" "4~%" "5~%") do 
        (format stream x)
        (force-output stream)
        (sleep 1)
        ;;(format t "~A~%" (read-line stream))
    )
    )
)
(start-client)

该代码运行良好,但注释行除外:

(format t "~A~%" (read-line stream))

所以我能够从另一个套接字(另一个程序)发送和接收消息 1,2,3 ...,并将消息从另一个程序发送回 lisp。但是,当我取消注释从 lisp 读取消息的行时,上面的代码似乎停止并永远等待。

4

1 回答 1

1

在不了解服务器的情况下,很难说出您的问题是什么。也许它永远不会终止线路?

这是一个小演示,使用线程来隔离客户端和服务器:

(in-package #:cl-user)

(eval-when (:compile-toplevel :load-toplevel :execute)
  (ql:quickload '("usocket" "bordeaux-threads")))

(defpackage #:usocket-demo
  (:use #:cl))

(in-package #:usocket-demo)

(defun serve (port)
  "Starts a socket server to answer a single request."
  (usocket:with-socket-listener (server-socket "0.0.0.0" port
                                               :reuse-address t)
    (let* ((stream-socket (usocket:socket-accept server-socket))
           (server-stream (usocket:socket-stream stream-socket))
           (request (read-line server-stream)))           ; read
      (format t "S> serving…~%")
      (format server-stream "Hello, ~a!~%" request)       ; write
      (finish-output server-stream))))

(defun cly (port)
  "Makes a single request to a server and prints the answer."
  (usocket:with-client-socket (client-socket client-stream "0.0.0.0" port)
    (format client-stream "Issa me!~%")                   ; write
    (finish-output client-stream)
    (let ((response (read-line client-stream)))           ; read
      (format t "C> I got a response: ~a~%" response))))

(defun run-demo ()
  (let ((bt:*default-special-bindings*
          `((*standard-output* . ,*standard-output*))))
    (bt:make-thread (lambda ()
                      (serve 13575))
                    :name "Server")
    (bt:make-thread (lambda ()
                      (cly 13575))
                    :name "Client")
    (values)))

的绑定bt:*default-special-bindings是必要的,这样线程才能看到演示消息的相同输出流。

如您所见,客户端和服务器都有一个可以读取和写入的流。

于 2018-09-10T21:40:00.993 回答