sockjs - 实施房间的例子

时间:2013-04-15 20:11:50

标签: python tornado sockjs

我希望让用户创建并加入“房间”,以便他们可以协作。

我正在查看SockJs Multiplexer server并想知道我是否可以利用其中一些来创建和广播到特定的频道/房间。

在示例中,channel is created manuallyclient connects to that channel

将这些频道视为会议室吗?

有没有办法动态创建这些频道而不是在服务器上手动声明它们?

1 个答案:

答案 0 :(得分:3)

免责声明:在我写完答案之前,我没有注意到你指的是服务器的Javascript版本。因此,我的代码示例是使用基于Python的sockjs-tornado给出的,但我想原则应该是相同的。

是的,您可以通过在每个SockJSConnection派生类中保留一组引用的连接来将通道视为空间。要做到这一点,您只需要从

稍微更改每个连接类
class AnnConnection(SockJSConnection):
    def on_open(self, info):
        self.send('Ann says hi!!')

    def on_message(self, message):
        self.broadcast(self.connected, 'Ann nods: ' + message)

class AnnConnection(SockJSConnection):
    connected = WeakSet()

    def on_open(self, info):
        self.connected.add(self)
        self.send('Ann says hi!!')

    def on_message(self, message):
        self.broadcast(self.connected, 'Ann nods: ' + message)

    def on_close(self):
        self.connected.remove(self)
        super(AnnConnection, self).on_close()
<{3>}中的

要动态创建频道,我稍微更改了__main__代码和MultiplexConnection类,并添加了几个新类。在if __name__ == "__main__":块中,

# Create multiplexer
router = MultiplexConnection.get(ann=AnnConnection, bob=BobConnection,
                                 carl=CarlConnection)

已更改为

# Create multiplexer
router = MultiplexConnection.get()

虽然

class MultiplexConnection(conn.SockJSConnection):
    channels = dict()
    # …

    def on_message(self, msg):
        # …
        if chan not in self.channels:
            return
server.py中的

已更改为

class MultiplexConnection(conn.SockJSConnection):
    channels = dict()
    _channel_factory = ChannelFactory()
    # …

    def on_message(self, msg):
        # …
        if chan not in self.channels:
            self.channels[chan] = self._channel_factory(chan)

和班级

class DynamicConnection(SockJSConnection):
    def on_open(self, info):
        self.connected.add(self)
        self.send('{0} says hi!!'.format(self.name))

    def on_message(self, message):
        self.broadcast(self.connected, '{0} nods: {1}'
            .format(self.name, message))

    def on_close(self):
        self.connected.remove(self)
        super(DynamicConnection, self).on_close()


class ChannelFactory(object):
    _channels = dict()

    def __call__(self, channel_name):
        if channel_name not in self._channels:
            class Channel(DynamicConnection):
                connected = WeakSet()
                name = channel_name

            self._channels[channel_name] = Channel

        return self._channels[channel_name]

已添加到MultiplexConnection