1

我正在尝试让 python 程序和 Allegro Common Lisp 程序通过套接字进行通信。现在,我正在尝试设置一个监听连接的 Lisp 服务器,让一个 python 客户端连接到服务器,然后从客户端向服务器发送一条简单的消息。Lisp 服务器如下所示:

(let ((socket (socket:make-socket :connect :passive
                              :type :stream
                              :address-family :internet
                              :local-port 45676)))
  (format t "opened up socket ~A for connections~%" socket)

  ;; now wait for connections and accept
  (let ((client (socket:accept-connection socket 
                                      :wait t)))
    (when client
      ;; we've got a new connection from client
      (format t "got a new connection from ~A~%" client)

      ;; now wait for data from client
      (loop until (listen client) do
        (format t "first character seen is ~A~%" (peek-char t client))
        (let ((data (read-line client)))
          (format t "data received: ~A~%" data))))))

python 客户端如下所示:

import socket
import time
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
s.connect (('', 45676))
time.sleep (1) # works if uncommented, does not work if commented
s.sendall ("(list A B)")
s.close ()

因为我想让多条消息通过这个流,我在服务器端监听传入的数据,然后回显它。但是,当我使用注释的 sleep 命令运行它时,我注意到了一个问题。输出看起来像这样:

opened up socket #<MULTIVALENT stream socket waiting for connection
                   at */45676 @ #x207b0cd2> for connections
got a new connection from #<MULTIVALENT stream socket connected from
                            localhost/45676 to localhost/60582 @
                            #x207b34f2>

换句话说,它实际上并没有回显数据(在我的例子中,“(列表 AB)”)。如果我取消注释 sleep 命令(在连接启动和数据发送之间引入一些延迟),输出如下所示:

opened up socket #<MULTIVALENT stream socket waiting for connection
                   at */45676 @ #x207b0bea> for connections
got a new connection from #<MULTIVALENT stream socket connected from
                            localhost/45676 to localhost/60572 @
                            #x207b340a>
data received: (list A B)

我不确定为什么会这样。有人对此有解决方案吗?为多次数据交换重用同一个套接字连接是不是一个坏主意?如果我删除整个循环宏调用(并因此使其成为一次性交换),则接收到的数据没有任何问题并正确回显

编辑 1:即使注释了 sleep 命令,最后一条语句也是正确的。

4

0 回答 0