2013-04-15 69 views

回答

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

+0

嗨馬丁,我面臨麻煩,使我的聊天交互私人(一對一)。你可以看看http://stackoverflow.com/questions/34461046/private-messaging-using-sockjs-tornado/34463050#34463050? –

+0

感謝您伸出援手,Sathish。我剛寫了我的[建議的解決方案](http://stackoverflow.com/a/34466792/126273)。 –