【发布时间】:2021-04-25 13:38:59
【问题描述】:
TL;DR
我使用pynng 启动一个服务器,然后来自Python 标准库socket 的客户端 将尝试向它发送消息。
问题是 client 可以发送消息,但 server 没有注意到它。因此,它不起作用。
我错过了什么吗?一些低级协议设置?一些终止字符?
我这样做的原因是我将构建一个使用pynng 充当服务器的Python 脚本。然后一个非 Python 程序(我假设它具有基本 TCP 协议的知识)将尝试与这个 Python 服务器通信。因此,我使用的是恕我直言,我可以操作的最原始的套接字库,标准库中的 socket 模块。
详情
我将在讨论时展示代码 sn-ps,但我将在最后展示完整的最小代码示例。
我正在尝试使用 pynng 启动服务器
def server():
with pynng.Pair0(listen=f'tcp://{HOST:s}:{PORT:d}', recv_timeout=10000) as s:
print("Server running")
data = s.recv() # Blocks forever here
print(data)
然后,看起来像这样的客户端将尝试连接到它:
def client():
with socket.create_connection(address=(HOST, PORT), timeout=5) as s:
print("Client connected")
s.sendall(b'Hello world')
print("Client sent message")
我把它们放在一起使用threading:
def main():
srv = threading.Thread(target=server)
cli = threading.Thread(target=client)
srv.start()
cli.start()
srv.join()
cli.join()
最低工作代码
总而言之,这是最低工作代码:
import socket
import pynng
import threading
HOST = "127.0.0.1"
PORT = 65432
def main():
srv = threading.Thread(target=server)
cli = threading.Thread(target=client)
srv.start()
cli.start()
srv.join()
cli.join()
def server():
with pynng.Pair0(listen=f'tcp://{HOST:s}:{PORT:d}', recv_timeout=10000) as s:
print("Server running")
data = s.recv() # Blocks forever here
print("Message received")
print(data)
def client():
with socket.create_connection(address=(HOST, PORT), timeout=5) as s:
print("Client connected")
s.sendall(b'Hello world')
print("Client sent message")
if __name__ == "__main__":
main()
然后我在终端运行这个
$ python main.py
似乎server 无法发送recv 消息,因此recv 尝试在10000 毫秒时超时。
Server running
Client connected
Client sent message
Exception in thread Thread-1:
Traceback (most recent call last):
File "/home/kmonisit/miniconda3/envs/engg/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/home/kmonisit/miniconda3/envs/engg/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "main.py", line 39, in server
data = s.recv() # Blocks forever here
File "/home/kmonisit/miniconda3/envs/engg/lib/python3.8/site-packages/pynng/nng.py", line 454, in recv
check_err(ret)
File "/home/kmonisit/miniconda3/envs/engg/lib/python3.8/site-packages/pynng/exceptions.py", line 201, in check_err
raise exc(string, err)
pynng.exceptions.Timeout: Timed out
【问题讨论】:
-
不知道
nng以及它使用什么协议,但很可能它不将“hello, world”识别为完整且有效的输入。 -
是的,即使是空白的
s.sendall(b'')也会超过pynng的头。
标签: python sockets server tcp pynng