2017-05-07 59 views
1

我已经经历了许多论坛和网站,但没有找到任何可以解决我的问题的解决方案。如何通过python autobahn/twisted发送有效载荷给特定用户

我有这个server.py文件:

from autobahn.twisted.websocket import WebSocketServerProtocol, \ 
WebSocketServerFactory 


class MyServerProtocol(WebSocketServerProtocol): 

    def onConnect(self, request): 
     print("Client connecting: {0}".format(request.peer)) 

    def onOpen(self): 
     print("WebSocket connection open.") 

    def onMessage(self, payload, isBinary): 
     if isBinary: 
      print("Binary message received: {0} bytes".format(len(payload))) 
     else: 
      print("Text message received: {0}".format(payload.decode('utf8'))) 
      print("Text message received: {0}".format(self.peer)) 


     # echo back message verbatim 
     self.sendMessage(payload, isBinary) 

    def onClose(self, wasClean, code, reason): 
     print("WebSocket connection closed: {0}".format(reason)) 


if __name__ == '__main__': 

    import sys 

    from twisted.python import log 
    from twisted.internet import reactor 

    log.startLogging(sys.stdout) 

    factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") 
    factory.protocol = MyServerProtocol 
    # factory.setProtocolOptions(maxConnections=2) 

    # note to self: if using putChild, the child must be bytes... 

    reactor.listenTCP(9000, factory) 
    reactor.run() 

我想要做的就是里面的onMessage我想从客户端接收有效载荷,然后发送有效载荷到另一个客户端,我不希望将有效负载回送给同一个客户端。

目前我可以成功接收有效载荷。但是,如何将有效载荷发送给不同的客户端?

我在许多网站上看到类似的问题,但没有一个帮助。

回答

0

这是一个关于FAQ“How do I make input on one connection result in output on another?

从本质上讲,你只需要在协议的基准为其他连接,因此您可以在其上调用sendMessage的变化。该参考可以采用MyServerProtocol或工厂或其他对象上的属性形式。也许它会直接引用另一个协议实例,或者它可能是一个用于更复杂交互的集合(列表,字典,集合)。

一旦你有了参考资料,你就可以拨打sendMessage,并且信息会发送到该连接,而不是self表示的连接。

相关问题