【问题标题】:how to send payload to specific user by python autobahn/twisted如何通过 python autobahn/twisted 向特定用户发送有效负载
【发布时间】:2017-05-07 06:25:03
【问题描述】:

我浏览了许多论坛和网站,但没有找到任何可以解决我的问题的解决方案。

我有这个 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 内部我想从客户端接收有效负载,然后将该有效负载发送到另一个客户端,我不想将有效负载回显到同一个客户端。

目前我可以成功接收到payload。但是将该有效负载发送到不同客户端的方法是什么?

我在很多网站上都看到过类似的问题,但都没有帮助。

【问题讨论】:

    标签: websocket twisted autobahn


    【解决方案1】:

    这是常见问题解答“How do I make input on one connection result in output on another?”的变体

    本质上,您只需要对另一个连接的协议的引用,就可以在其上调用sendMessage。该引用可能采用MyServerProtocol 或工厂或其他对象上的属性的形式。可能是对另一个协议实例的直接引用,也可能是用于更复杂交互的集合(列表、字典、集合)。

    获得参考后,只需使用它调用sendMessage,消息就会转到该连接,而不是self 所代表的连接。

    【讨论】:

      猜你喜欢
      • 2016-03-25
      • 1970-01-01
      • 2020-07-26
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 2018-11-23
      • 1970-01-01
      相关资源
      最近更新 更多