python - 在单独的线程中运行的高速公路外部的 sendMessage

标签 python autobahn

我想从 MyServerProtocol 类外部调用 sendMessage 方法并向连接的客户端发送消息。我使用 threading 来做到这一点。

当我使用这段代码时:

from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
from twisted.internet import reactor
import threading

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')))

        self.sendMessage(payload, isBinary)

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


class Connection(threading.Thread):
    def __init__(self):
        super(Connection, self).__init__()

    def run(self):
        self.factory = WebSocketServerFactory("ws://localhost:9000", debug=False)
        self.factory.protocol = MyServerProtocol
        reactor.listenTCP(9000, self.factory)
        reactor.run(installSignalHandlers=0)

    def send(self, data):
        reactor.callFromThread(self.factory.protocol.sendMessage, self.factory.protocol, data)

connection = Connection()
connection.daemon = True
connection.start()
connection.send('test')

发生此错误:

connection.send('test')
reactor.callFromThread(self.factory.protocol.sendMessage, self.factory.protocol, data)
AttributeError: 'Connection' object has no attribute 'factory'

如果我尝试注释掉 connection.send('test') 行,则会发生此错误:

TypeError: 'NoneType' object is not iterable

我的代码有什么问题?

我这样做是否正确?或者是否有另一种方法可以从协议(protocol)类外部向客户端发送消息?

谢谢。

最佳答案

is [there] another way to send clients message from outside of server class?

我做这样的事情来发送消息。我使用 twisted 来运行我的网络应用程序。

import json
from autobahn.twisted.websocket import WebSocketServerProtocol
from twisted.internet import reactor

class MyProtocol(WebSocketServerProtocol):
    connections = list()

    def onConnect(self, request):
        self.connections.append(self)

    def onClose(self, wasClean, code, reason):
        self.connections.remove(self)

    @classmethod
    def broadcast_message(cls, data):
        payload = json.dumps(data, ensure_ascii = False).encode('utf8')
        for c in set(cls.connections):
            reactor.callFromThread(cls.sendMessage, c, payload)


# Somewhere else
MyProtocol.broadcast_message({'greeting': 'Hello world'})

我不知道它是否是 The Right Way™,但它对我来说效果很好。

关于python - 在单独的线程中运行的高速公路外部的 sendMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799754/

相关文章:

python - 如何防止应用程序在调用 get_multi 时调用 datastore_v3.next()?

python - Web 套接字服务器的后台任务

javascript - WebSocket react native

memory-leaks - Python 安全 websocket 内存消耗

python - 如何从单个 pandas.apply() 调用形成乘列?

python - 如何将多个循环合并为一个循环?

python - 标题后有多余的空行

python - 以下原则对于 autobahn python 是否正确?

javascript - 扭曲的 websocket 聊天服务器 openid 身份验证

python - Scrapy 没有使用 extract_first() 获得干净的文本