1

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

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

在示例中,手动创建了一个通道客户端连接到该通道

将这些频道视为房间有效吗?

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

4

1 回答 1

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()

server.py中。

为了动态创建通道,我稍微更改了__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

MultiplexConnection更改为

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]

被添加到multiplex.py

于 2013-05-14T09:24:42.067 回答