2017-05-07 39 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表示的連接。

相關問題