python Socket.IO客户端,用于向TornadIO2服务器发送广播消息

Alp*_*Alp 19 python django tornado websocket socket.io

我正在构建一个实时Web应用程序.我希望能够从我的python应用程序的服务器端实现发送广播消息.

这是设置:

我可以成功地将socket.io消息从客户端发送到服务器.服务器处理这些并可以发送响应.在下面我将描述我是如何做到的.

当前设置和代码

首先,我们需要定义一个处理socket.io事件的Connection:

class BaseConnection(tornadio2.SocketConnection):
    def on_message(self, message):
        pass

    # will be run if client uses socket.emit('connect', username)
    @event
    def connect(self, username):
        # send answer to client which will be handled by socket.on('log', function)
        self.emit('log', 'hello ' + username)
Run Code Online (Sandbox Code Playgroud)

启动服务器是由Django管理自定义方法完成的:

class Command(BaseCommand):
    args = ''
    help = 'Starts the TornadIO2 server for handling socket.io connections'

    def handle(self, *args, **kwargs):
        autoreload.main(self.run, args, kwargs)

    def run(self, *args, **kwargs):
        port = settings.SOCKETIO_PORT

        router = tornadio2.TornadioRouter(BaseConnection)

        application = tornado.web.Application(
            router.urls,
            socket_io_port = port
        )

        print 'Starting socket.io server on port %s' % port
        server = SocketServer(application)
Run Code Online (Sandbox Code Playgroud)

很好,服务器现在运行.让我们添加客户端代码:

<script type="text/javascript">    
    var sio = io.connect('localhost:9000');

    sio.on('connect', function(data) {
        console.log('connected');
        sio.emit('connect', '{{ user.username }}');
    });

    sio.on('log', function(data) {
        console.log("log: " + data);
    });
</script>
Run Code Online (Sandbox Code Playgroud)

显然,{{ user.username }}将被当前登录用户的用户名替换,在此示例中,用户名为"alp".

现在,每次刷新页面时,控制台输出为:

connected
log: hello alp
Run Code Online (Sandbox Code Playgroud)

因此,调用消息和发送响应有效.但现在是棘手的部分.

问题

响应"hello alp"仅发送给socket.io消息的调用者.我想向所有连接的客户端广播消息,以便在新用户加入聚会时(例如在聊天应用程序中)可以实时通知他们.

所以,这是我的问题:

  1. 如何向所有连接的客户端发送广播消息?

  2. 如何向在特定频道上订阅的多个已连接客户端发送广播消息?

  3. 如何在我的python代码(BaseConnection课堂外)的任何地方发送广播消息?这需要某种用于python的Socket.IO客户端,还是内置TornadIO2?

所有这些广播应该以可靠的方式完成,所以我认为websockets是最好的选择.但我对所有好的解决方案持开放态度.

Yuv*_*dam 16

我最近在类似的设置上写了一个非常相似的应用程序,所以我有几个见解.

做你需要的正确方法是有一个pub-sub后端.你可以用简单的ConnectionHandlers 做很多事情.最终,处理类级别的连接开始变得丑陋(更不用说错误了).

理想情况下,你想使用像Redis这样的东西,对龙卷风进行异步绑定(查看brukva).这样你就不必将客户端注册到特定的频道 - Redis拥有开箱即用的所有功能.

基本上,你有这样的事情:

class ConnectionHandler(SockJSConnection):
    def __init__(self, *args, **kwargs):
        super(ConnectionHandler, self).__init__(*args, **kwargs)
        self.client = brukva.Client()
        self.client.connect()
        self.client.subscribe('some_channel')

    def on_open(self, info):
        self.client.listen(self.on_chan_message)

    def on_message(self, msg):
        # this is a message broadcast from the client
        # handle it as necessary (this implementation ignores them)
        pass

    def on_chan_message(self, msg):
        # this is a message received from redis
        # send it to the client
        self.send(msg.body)

    def on_close(self):
        self.client.unsubscribe('text_stream')
        self.client.disconnect()
Run Code Online (Sandbox Code Playgroud)

请注意,我使用sockjs-tornado,我发现它比socket.io更稳定.

无论如何,一旦你有这种设置,从任何其他客户端(例如Django,在你的情况下)发送消息就像打开Redis连接(redis-py是一个安全的赌注)并发布消息一样简单:

import redis
r = redis.Redis()
r.publish('text_channel', 'oh hai!')
Run Code Online (Sandbox Code Playgroud)

这个答案结果很长,所以我加倍努力,发了一篇博客文章:http://blog.y3xz.com/blog/2012/06/08/a-modern-python-stack-for-一个实时的Web应用程序/

  • 当然.我也开始使用socket.io,并且实际上与MrJoes(tornadio/sockjs-tornado maintainer)进行了讨论.他声称sockjs有100%的测试覆盖率,而且已知socket.io有一些协议错误.我发现这是真的,当进入生产时,sockjs确实感觉更加坚固(尽管我们确实有一些与运输无关的其他问题). (4认同)
  • @Alp - 对于"常规"应用程序,此设置就像一个魅力.我构建的应用程序*严重*消息(每秒几十条消息,不要问;))事实证明Chrome真的不喜欢那些东西.在使用此类WebSocket 1-5分钟后,Chrome将崩溃. (2认同)