列表中的双向插座

时间:2018-09-10 13:49:08

标签: sockets lisp usocket

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

到目前为止,我已收到以下代码:

Offset()

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

(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)

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

1 个答案:

答案 0 :(得分: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的绑定是必要的,这样线程才能为演示消息看到相同的输出流。

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