Tôi muốn gọi phương thức sendMessage
từ bên ngoài của MyServerProtocol
lớp và gửi tin nhắn đến các khách hàng được kết nối. Tôi sử dụng threading
để thực hiện việc này.sendMessage từ bên ngoài trong autobahn chạy trong thread riêng biệt
Khi tôi sử dụng mã này:
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')
lỗi này xảy ra:
connection.send('test')
reactor.callFromThread(self.factory.protocol.sendMessage, self.factory.protocol, data)
AttributeError: 'Connection' object has no attribute 'factory'
Nếu tôi cố gắng xóa bỏ dòng connection.send('test')
, lỗi này xảy ra:
TypeError: 'NoneType' object is not iterable
gì vấn đề với mã của tôi là gì?
Tôi có làm đúng cách này không? Hoặc là có một cách khác để gửi tin nhắn cho khách hàng từ bên ngoài của lớp giao thức?
Cảm ơn.
Có self.factory tồn tại khi bạn gọi gửi không? Cố gắng đặt một giấc ngủ giữa start() và send() và kiểm tra. Ngoài ra, hãy sử dụng trình gỡ lỗi. – Raito
Bạn đã bao giờ tìm ra cách để làm điều này? Tôi đang gặp vấn đề tương tự. – someuser