Python asyncio资源不可用

时间:2017-06-14 15:46:47

标签: python asynchronous exception-handling server python-asyncio

我有一个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函数中发生错误。

如何修复此可用性错误?

1 个答案:

答案 0 :(得分:1)

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()