How to run functions outside websocket loop in python (tornado)

后端 未结 3 1242
[愿得一人]
[愿得一人] 2020-12-08 00:52

I\'m trying to set up a small example of a public Twitter stream over websockets. This is my websocket.py, and it\'s working.

What I\'m wondering is: how can I inte

3条回答
  •  [愿得一人]
    2020-12-08 01:18

    I stumbled upon similar problem. Here is my solution. Hope this will be helpful to someone out there

    wss = []
    class wsHandler(tornado.websocket.WebSocketHandler):
        def open(self):
            print 'Online'
            if self not in wss:
                wss.append(self)
    
        def on_close(self):
            print 'Offline'
            if self in wss:
                wss.remove(self)
    
    def wsSend(message):
        for ws in wss:
            ws.write_message(message)
    

    To send message to your websockets simply use this:

    wsSend(message)
    

    wsSend update

    I've been getting exceptions with wsSend once in a while. In order to fix it I've modified code a bit to following:

    def wsSend(message):
        for ws in wss:
            if not ws.ws_connection.stream.socket:
                print "Web socket does not exist anymore!!!"
                wss.remove(ws)
            else:
                ws.write_message(message)
    

提交回复
热议问题