import trio
from trio import socket
async def listen(host, port):
while True:
fullmsg = ""
sock = socket.socket()
await sock.bind((host, port))
sock.listen()
print(f'Awaiting Receive On {host}:{port}')
conn, addr = await sock.accept()
print(f'Connection Received From {addr[0]}:{addr[1]}')
while True:
try:
msg = await conn.recv(8)
if len(msg.decode().strip()) > 0:
print(f'Received {len(msg.strip())} bytes')
fullmsg += msg.decode().strip()
else:
break
except Exception as e:
print(f'DEBUG: {e}')
sock.shutdown(0)
sock.close()
print(fullmsg)
# function that runs the listen function:
async def create():
async with trio.open_nursery() as nursery:
nursery.start_soon(listen, '127.0.0.1', 6969)
# To run the program
trio.run(create)
我想在每次收到长度为0的消息时或在客户端关闭连接时一遍又一遍地运行该函数,但是当该函数完成第一个while循环的第一次迭代时,它给出OSError表示端口已在正在使用。我在循环结束时关闭并关闭了套接字,但我仍然不知道程序在哪里出错。
Awaiting Receive On 127.0.0.1:6969
Connection Received From 127.0.0.1:37122
Received 8 bytes
Received 5 bytes
Hello, World!
Traceback (most recent call last):
File "./ape.py", line 68, in <module>
trio.run(create)
File "/usr/local/lib/python3.8/dist-packages/trio/_core/_run.py", line 1804, in run
raise runner.main_task_outcome.error
File "./ape.py", line 59, in create
nursery.start_soon(listen, '127.0.0.1', 6969)
File "/usr/local/lib/python3.8/dist-packages/trio/_core/_run.py", line 730, in __aexit__
raise combined_error_from_nursery
File "./ape.py", line 15, in listen
await sock.bind((host, port))
File "/usr/local/lib/python3.8/dist-packages/trio/_socket.py", line 473, in bind
return self._sock.bind(address)
OSError: [Errno 98] Address already in use
就像其他人在评论中说的那样,问题在于,在Unix-y平台上,SO_REUSEADDR
如果要能够关闭监听套接字,然后立即打开绑定到同一端口的新套接字,则必须设置套接字选项。
但是请注意,在Windows上,永远不要设置该SO_REUSEADDR
选项,因为在Windows上,默认情况下启用了所需的行为,并且SO_REUSEADDR
将其重新定义为“关闭安全性”选项。
trio.socket
是非常低级的,并公开了所有这些细节,因此,如果您想自己处理这些细节,则可以这样做。但是,大多数用户使用诸如的高级帮助程序会更好trio.serve_tcp
,它将自动处理很多此类详细信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句