2024-06-06 08:06:58 发布
网友
我想让用户创建和加入一个“房间”,以便他们可以合作。在
我在看SockJs Multiplexer server并想知道我是否可以利用其中的一些来创建并广播到特定的频道/房间。在
在本例中,a channel is created manually和client connects to that channel。在
把这些通道当作房间处理行吗?在
有没有一种方法可以动态创建这些通道,而不是在服务器上手动声明它们?在
在 免责声明:在我写完答案之前,我没有注意到你指的是服务器的Javascript版本。因此,我的代码示例是使用基于Python的sockjs-tornado给出的,但我想原理应该是相同的。在
是的,您可以通过在每个SockJSConnection-派生类中保留一组引用的连接来将通道视为房间。要做到这一点,您需要做的就是将每个连接类从
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)
到
在server.py中。在
为了动态地创建频道,我稍微修改了__main__代码和MultiplexConnection类,并添加了两个新类。在if __name__ == "__main__":块中
__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。在
在 免责声明:在我写完答案之前,我没有注意到你指的是服务器的Javascript版本。因此,我的代码示例是使用基于Python的sockjs-tornado给出的,但我想原理应该是相同的。在
是的,您可以通过在每个
SockJSConnection
-派生类中保留一组引用的连接来将通道视为房间。要做到这一点,您需要做的就是将每个连接类从到
^{pr2}$在server.py中。在
为了动态地创建频道,我稍微修改了
__main__
代码和MultiplexConnection
类,并添加了两个新类。在if __name__ == "__main__":
块中已更改为
同时
在MultiplexConnection中更改为
课程呢
添加到multiplex.py。在
相关问题 更多 >
编程相关推荐