Python asynchronous callback becomes synchronous and implements timeout
过去多啦不再A梦
过去多啦不再A梦 2017-05-18 11:00:46
0
1
770

Scenario: There is a server A and a client B, and there is a socket connection.
What we are writing now is part B of the client, which is not controllable by the server.
It turns out that B sends a packet first, waits for A to return the specified content, and then B sends the next packet


def do():
    s.send(...)
    yield 1
    s.send(...)
    yield 2
    
    
# 接收到数据后的回调
def callback():
    global f
    next(f)
    
f=do()
next(f)

Now I want to implement a timeout and implement blocking. After B sends the data, it blocks until A returns the data (or raises an error if it does not receive a return from A within 5 seconds). Please tell me how to achieve this?

过去多啦不再A梦
过去多啦不再A梦

reply all(1)
黄舟

With Tornado, I can’t write more than a few lines of code.

Let’s make a simple Server first to facilitate demonstration:

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

Then, to implement Client, the basic logic is to close the connection when timeout occurs, and then re-establish the connection:

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


Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template