作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
代码
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)
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
如果您希望能够关闭监听套接字,然后立即打开一个绑定(bind)到同一端口的新套接字,请使用套接字选项。
但请注意,在 Windows 上,您永远不应该设置 SO_REUSEADDR
选项,因为在 Windows 上,您想要的行为默认启用,SO_REUSEADDR
被重新定义为“关闭安全”选项。trio.socket
非常底层并且暴露了所有这些细节,所以如果你想自己处理它们,它可以让你这样做。但大多数用户最好使用更高级的助手,如 trio.serve_tcp
。 ,它将自动处理很多这些细节。
关于python-asyncio - 获取 OSError : (Address already in use) while runnning a function that uses trio-sockets in a while loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60616038/
代码 import trio from trio import socket async def listen(host, port): while True: fullmsg
我是一名优秀的程序员,十分优秀!