gpt4 book ai didi

Python asyncio 资源不可用

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:12 24 4
gpt4 key购买 nike

我有一个 python 服务器,它应该连续发送数据并等待客户端提示停止、设置变量或传输日志文件的内容。目前我只是想恢复客户端的提示。

我正在尝试利用 asyncio 来执行此操作,但遇到以下错误:

(, BlockingIOError(11, '资源暂时不可用'), )

我的服务器代码是:

loop = asyncio.get_event_loop()

async def server():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

host = ''
port = 1194

s.bind((host,port))
print ("bouned to port")
s.listen(4)
while True:

conn, addr = await loop.sock_accept(s)

if conn:
print ("connected to address: {!r}".format(addr))
# print (conn)
d = loop.create_task(temp_sender(conn))
try:
await d
except StopIteration:
pass
async def temp_sender(conn):
print("temp_sender activated")

try:
data = await conn.recv(1024)
print (data)
sdata = data.decode()
print (sdata)
conn.writeline("the set temp is: ", sdata)
except:
print (sys.exc_info())
pass

尝试从 conn 接收数据时,temp_sender 函数中发生错误。

如何修复此可用性错误?

最佳答案

import asyncio
@asyncio.coroutine
def handle_echo(reader, writer):
data = yield from reader.read(1024)
# reader reads from client
#writer writes to client

message = data
addr = writer.get_extra_info('peername')
print("Received %r from %r" % (message, addr))

print("Send: %r" % message)
writer.write(data)
yield from writer.drain()

print("Closing client socket")
writer.close()

loop = asyncio.get_event_loop()
##the code below will run whenever a new client connects ( multiple at a time)
coro = asyncio.start_server(handle_echo, '127.0.0.1',1194, loop=loop)
server = loop.run_until_complete(coro)

# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt: #server stops on a keyboard interrupt
pass

# Closing the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()

关于Python asyncio 资源不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44549297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com