简体   繁体   English

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

[英]sendMessage from outside in autobahn running in separate thread

I want to call sendMessage method from outside of MyServerProtocol class and send a message to connected clients.我想从MyServerProtocol类外部调用sendMessage方法并向连接的客户端发送消息。 I use threading to do this.我使用threading来做到这一点。

When I use this code :当我使用此代码时:

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

this error happens:发生此错误:

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

If I try to comment out the line connection.send('test') , this error happens:如果我尝试注释掉connection.send('test') ,则会发生此错误:

TypeError: 'NoneType' object is not iterable

What is the problem with my code ?我的代码有什么问题?

Am I doing this the right way?我这样做是否正确? Or is there another way to send message to clients from outside of the protocol class?或者是否有另一种方法可以从协议类之外向客户端发送消息?

Thanks.谢谢。

is [there] another way to send clients message from outside of server class? [有]另一种从服务器类外部发送客户端消息的方法吗?

I do something like this to send message.我做这样的事情来发送消息。 I use twisted to run my web app.我使用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'})

I do not know if it is The Right Way ™, but it works well for me.我不知道它是否是The Right Way ™,但它对我来说效果很好。

add self.factory to your "init(self):" see below:将 self.factory 添加到您的“init(self):”中,如下所示:

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,factory):
            super(Connection, self).__init__()
            self.factory=WebSocketServerFactory("ws://localhost:9000", debug=False)
        def run(self):
            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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM