简体   繁体   中英

Handling websockets in python

I am developing a messaging service that uses websockets. And I shall be using python/django as a server side language. There are options such as:

  1. Tornado
  2. django-websockets-redis
  3. Crossbar.io
  4. Flask-SocketIO

I am confused by what should I be using for the production environment where the number of active connections is large.

Websockets in tornado are relatively straightforward. This example shows how you can integrate websockets with extremely basic management ( open and on_close methods).

For upstream traffic (browser -> server) you can implement the WebSocketHandler methods:

def on_message(self, message):
    # call message callback

def data_received(self, chunk):
    # do something with chunked data

For downstream traffic, there's WebSocketHandler.write_message :

def broadcast_to_all_websockets(self, message):
    for ws in cl:
        if not ws.ws_connection.stream.socket:
            print "Web socket %s does not exist anymore!" % ws
            cl.remove(ws)
        else:
            ws.write_message(message)

Highly suggest using autobahn|Python . Currently using it right now for a WebSocket project in Python and it's so easy to work with and has a lot of classes already built for you like a WebSocketServer. Let's you choose your implementation too (choice between asyncio and Twisted.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM