python同步异步,python异步回调转为同步并实现超时

用 Tornado 的话,写不了几行代码吧。

先作个简单的 Server ,以方便演示:

# -*- coding: utf-8 -*-

from tornado.ioloop import IOLoop

from tornado.tcpserver import TCPServer

from tornado import gen

class Server(TCPServer):

@gen.coroutine

def handle_stream(self, stream, address):

while 1:

data = yield stream.read_until('\n')

if data.strip() == 'exit':

stream.close()

break

if data.strip() == '5':

IOLoop.current().call_at(IOLoop.current().time() + 5, lambda: stream.write('ok 5\n'))

else:

stream.write('ok\n')

if __name__ == '__main__':

Server().listen(8000)

IOLoop.current().start()

然后,来实现 Client ,基本逻辑是,超时就关闭连接,然后再重新建立连接:

# -*- coding: utf-8 -*-

import functools

from tornado.ioloop import IOLoop

from tornado.tcpclient import TCPClient

from tornado import gen

def when_error(stream):

print 'ERROR'

stream.close()

main()

@gen.coroutine

def main():

client = TCPClient()

stream = yield client.connect('localhost', 8000)

count = 0

IL = IOLoop.current()

while 1:

count += 1

stream.write(str(count) + '\n')

print count, '...'

timer = IL.call_at(IL.time() + 4, functools.partial(when_error, stream))

try:

data = yield stream.read_until('\n')

except:

break

IL.remove_timeout(timer)

print data

yield gen.Task(IL.add_timeout, IOLoop.current().time() + 1)

if __name__ == '__main__':

main()

IOLoop.current().start()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值