python異步回調(diào)轉(zhuǎn)為同步并實(shí)現(xiàn)超時(shí)
問(wèn)題描述
場(chǎng)景:一個(gè)服務(wù)端A,一個(gè)客戶(hù)端B,存在一個(gè)socket連接。現(xiàn)在寫(xiě)的是客戶(hù)端B部分,服務(wù)端不可控。原來(lái)是 B先發(fā)送一個(gè)包,等待A返回指定內(nèi)容,B再發(fā)送下一個(gè)包
def do(): s.send(...) yield 1 s.send(...) yield 2# 接收到數(shù)據(jù)后的回調(diào)def callback(): global f next(f) f=do()next(f)
現(xiàn)在想實(shí)現(xiàn)一個(gè)timeout,并且實(shí)現(xiàn)阻塞。B發(fā)送數(shù)據(jù)后阻塞,直到A返回?cái)?shù)據(jù)(或5秒內(nèi)未接受到來(lái)自A的返回raise一個(gè)錯(cuò)誤),請(qǐng)教如何實(shí)現(xiàn)?
問(wèn)題解答
回答1:用 Tornado 的話(huà),寫(xiě)不了幾行代碼吧。
先作個(gè)簡(jiǎn)單的 Server ,以方便演示:
# -*- coding: utf-8 -*-from tornado.ioloop import IOLoopfrom tornado.tcpserver import TCPServerfrom tornado import genclass 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 5n’)) else:stream.write(’okn’)if __name__ == ’__main__’: Server().listen(8000) IOLoop.current().start()
然后,來(lái)實(shí)現(xiàn) Client ,基本邏輯是,超時(shí)就關(guān)閉連接,然后再重新建立連接:
# -*- coding: utf-8 -*-import functoolsfrom tornado.ioloop import IOLoopfrom tornado.tcpclient import TCPClientfrom tornado import gendef when_error(stream): print ’ERROR’ stream.close() main()@gen.coroutinedef main(): client = TCPClient() stream = yield client.connect(’localhost’, 8000) count = 0 IL = IOLoop.current() while 1:count += 1stream.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: breakIL.remove_timeout(timer)print datayield gen.Task(IL.add_timeout, IOLoop.current().time() + 1)if __name__ == ’__main__’: main() IOLoop.current().start()
相關(guān)文章:
1. phpadmin的數(shù)據(jù)庫(kù),可以設(shè)置自動(dòng)變化時(shí)間的變量嗎?就是不需要接收時(shí)間數(shù)據(jù),自動(dòng)變化2. html5和Flash對(duì)抗是什么情況?3. 求救一下,用新版的phpstudy,數(shù)據(jù)庫(kù)過(guò)段時(shí)間會(huì)消失是什么情況?4. html - 爬蟲(chóng)時(shí)出現(xiàn)“DNS lookup failed”,打開(kāi)網(wǎng)頁(yè)卻沒(méi)問(wèn)題,這是什么情況?5. javascript - vue項(xiàng)目里的package.json6. ios - 為什么用WKWebView加載相同的html文本,有時(shí)展示的內(nèi)容卻不一樣。7. angular.js - vue中類(lèi)似于angular的ng-change的指令是?8. javascript - Ubuntu修改port后無(wú)法登陸9. boot2docker無(wú)法啟動(dòng)10. mac里的docker如何命令行開(kāi)啟呢?
