国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

python異步回調(diào)轉(zhuǎn)為同步并實(shí)現(xiàn)超時(shí)

瀏覽:119日期:2022-07-01 11:35:28

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

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 沙雅县| 靖州| 贞丰县| 新闻| 太保市| 韩城市| 南雄市| 尼勒克县| 崇阳县| 澜沧| 阳春市| 凯里市| 闽清县| 嘉善县| 建阳市| 固阳县| 唐山市| 镇康县| 鹤庆县| 金乡县| 五大连池市| 许昌市| 磐石市| 金堂县| 河北省| 天峨县| 固原市| 乐东| 大宁县| 禹州市| 柘荣县| 五华县| 金阳县| 五华县| 廉江市| 扎兰屯市| 萝北县| 临漳县| 城口县| 平凉市| 巫山县|