I want to call sendMessage
method from outside of MyServerProtocol
class and send a message to connected clients. I use threading
to do this.
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:
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.