Search code examples
pythonwebsockettornado

Websocket listen continuously after receiving response in tornado


I'm working on a websocket client listening to a tornado server. Once the client receives a message from server, the client is exiting silently.

Following is the code I've implemented.

#!/usr/bin/python

import tornado.websocket
from tornado import gen 
import requests

@gen.coroutine
def test_ws():
   client = yield tornado.websocket.websocket_connect("ws://localhost:8888/subscribe/ports")

msg = yield client.read_message()
print(msg)

if __name__ == "__main__":
    loop = tornado.ioloop.IOLoop()
    loop.run_sync(test_ws)

The client is running until it receives the first message from server. But I want to run indefinitely.

Am I missing something?


Solution

  • Use a loop:

    @gen.coroutine
    def test_ws():
        client = yield tornado.websocket.websocket_connect("ws://localhost:8888/subscribe/ports")
    
        while True:
            msg = yield client.read_message()
            print(msg)