gpt4 book ai didi

python - sockjs - 实现房间的示例

转载 作者:行者123 更新时间:2023-11-30 23:36:56 26 4
gpt4 key购买 nike

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

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

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

将这些 channel 视为房间可以吗?

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

最佳答案

免责声明:在我写下答案之前,我没有注意到您指的是服务器的 Javascript 版本。因此,我的代码示例是使用基于Python的sockjs-tornado给出的。 ,不过我想原理应该是一样的。

是的,您可以通过在每个 SockJSConnection 派生类中保留一组引用连接来将 channel 视为房间。为此,您需要的只是稍微更改每个连接类

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 .

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

# 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 .

关于python - sockjs - 实现房间的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16023933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com