Home  >  Q&A  >  body text

Python asynchronous callback becomes synchronous and implements timeout

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梦2711 days ago734

reply all(1)I'll reply

  • 黄舟

    黄舟2017-05-18 11:02:46

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

    reply
    0
  • Cancelreply