久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

python異步回調轉為同步并實現超時

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

問題描述

場景:一個服務端A,一個客戶端B,存在一個socket連接。現在寫的是客戶端B部分,服務端不可控。原來是 B先發送一個包,等待A返回指定內容,B再發送下一個包

def do(): s.send(...) yield 1 s.send(...) yield 2# 接收到數據后的回調def callback(): global f next(f) f=do()next(f)

現在想實現一個timeout,并且實現阻塞。B發送數據后阻塞,直到A返回數據(或5秒內未接受到來自A的返回raise一個錯誤),請教如何實現?

問題解答

回答1:

用 Tornado 的話,寫不了幾行代碼吧。

先作個簡單的 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()

然后,來實現 Client ,基本邏輯是,超時就關閉連接,然后再重新建立連接:

# -*- 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()

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 宁蒗| 剑河县| 武汉市| 景洪市| 湘乡市| 喀什市| 东海县| 铜陵市| 秦安县| 乌兰浩特市| 繁昌县| 读书| 阿瓦提县| 图片| 泸州市| 永平县| 信阳市| 丹阳市| 西盟| 林芝县| 天门市| 南康市| 桂东县| 当涂县| 钦州市| 南康市| 穆棱市| 德格县| 美姑县| 驻马店市| 湘阴县| 赞皇县| 卓资县| 定兴县| 榆林市| 闸北区| 吴桥县| 加查县| 内丘县| 铅山县| 海伦市|