我在Debian7服务器上的python3.4.2下遇到了一个奇怪的问题。我试着从客户端读取数据来检测它们是否断开连接,web上的大多数示例都使用这种方法,如果你读取了响应,并且它是空的,则断开循环并关闭连接。在
然而,在整整九次迭代之后,脚本将在read行上死掉,我甚至试图只在每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()
您应该在调试模式下运行程序以检测明显的异步错误。您在代码的不同位置忘记了“yield from”。在
https://docs.python.org/dev/library/asyncio-dev.html#debug-mode-of-asyncio
相关问题 更多 >
编程相关推荐