2017-05-07 2 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

これは基本的に「How do I make input on one connection result in output on another?

よくある質問のバリエーションであるあなたがそれにsendMessageを呼び出すことができますので、あなただけの他の接続のためのプロトコルへの参照が必要です。その参照は、あなたのMyServerProtocolの属性の形をとってもよいし、工場や他のオブジェクトの属性の形をとってもよい。多分、それは別のプロトコルインスタンスへの直接的な参照になるか、おそらくより複雑な相互作用のためのコレクション(リスト、辞書、セット)になるでしょう。

参照を取得したら、sendMessageを呼び出して、selfが表す接続ではなくその接続にメッセージが送られます。

関連する問題