Python 3.4.2 Asyncio Bug

时间:2014-11-20 04:02:45

标签: python python-3.x python-asyncio

我在Debian 7服务器上的Python 3.4.2下遇到了一个奇怪的问题。我正在尝试从客户端读取以检测它们是否断开连接,Web上的大多数示例都使用此方法,如果您读取响应并且它为空,则会中断循环并关闭连接。

然而,经过九次迭代后,脚本将在读取线上死亡,我甚至尝试仅在每次第10次迭代时进行读取,然后在90次迭代后死亡。如果我不尝试检测客户端断开连接,脚本将很乐意永远运行而不会出现问题。

原始代码基于此要点的服务器: https://gist.github.com/dbehnke/9627160

任何可能导致此问题的想法?

(脚本已完成,因此您可以自行运行以查看)

import asyncio
import logging

import json
import time

log = logging.getLogger(__name__)

clients = {}

def accept_client(client_reader, client_writer):
    task = asyncio.Task(handle_client(client_reader, client_writer))
    clients[task] = (client_writer)

    def client_done(task):
        del clients[task]
        client_writer.close()
        log.info("End Connection")

    log.info("New Connection")
    task.add_done_callback(client_done)


@asyncio.coroutine
def handle_client(client_reader, client_writer):
    data = {'result':{'status':'Connection Ready'}}
    postmessage(data,client_writer)
    count = 0
    while True:
        data = (yield from asyncio.wait_for(client_reader.readline(),timeout=1.0))
        if not data: #client disconnected
            break

        data = yield from asyncio.wait_for(test1(),timeout=1.0)
        yield from postmessage(data,client_writer)

        data = yield from asyncio.wait_for(test2(),timeout=1.0)
        yield from postmessage(data,client_writer)

@asyncio.coroutine
def postmessage(data, client_writer):
        mimetype=('text/event-stream')
        response = ('data: {0}\n\n'.format(data).encode('utf-8'))
        client_writer.write(response)
        client_writer.drain()

@asyncio.coroutine
def test1():
        data = {'result':{
                        'test1':{ }
                    }
                }
        data = json.dumps(data)
        return data

@asyncio.coroutine
def test2():
        data = {'result':{ 
                    'test2':{ }
                    }
                }
        data = json.dumps(data)
        return data 

def main():
    loop = asyncio.get_event_loop()
    f = asyncio.start_server(accept_client, host=None, port=2991)
    loop.run_until_complete(f)
    loop.run_forever()

if __name__ == '__main__':
    log = logging.getLogger("")
    formatter = logging.Formatter("%(asctime)s %(levelname)s " +
                                  "[%(module)s:%(lineno)d] %(message)s")
    # log the things
    log.setLevel(logging.DEBUG)
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    ch.setFormatter(formatter)
    log.addHandler(ch)
    main()

1 个答案:

答案 0 :(得分:0)

您应该以调试模式运行程序以检测明显的asyncio错误。你忘了"来自"在代码中的不同位置。

https://docs.python.org/dev/library/asyncio-dev.html#debug-mode-of-asyncio