MyServerProtocol
sınıfının dışından sendMessage
yöntemini aramak ve bağlı istemcilere bir ileti göndermek istiyorum. Bunu yapmak için threading
kullanıyorum.Dışarıdan iş parçacığı içinde ayrı bir iş parçacığı içinde çalışan ileti kutusu
Bu kodu kullandığınızda:
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')
bu hata olur:
connection.send('test')
reactor.callFromThread(self.factory.protocol.sendMessage, self.factory.protocol, data)
AttributeError: 'Connection' object has no attribute 'factory'
çizgiyi connection.send('test')
açıklama denerseniz, bu hata olur:
TypeError: 'NoneType' object is not iterable
neler kodumda sorun mu var?
Bunu doğru şekilde yapıyorum mu? Veya protokol sınıfının dışından müşterilere mesaj göndermek için başka bir yolu var mı?
Teşekkürler. senin "init (öz):" üzere
mu self.factory var? Start() ile send() arasında bir uyku koymayı ve kontrol etmeyi deneyin. Ayrıca, bir hata ayıklayıcı kullanın. – Raito
Hiç bunu nasıl anlamaya mı? Aynı problemi yaşıyorum. – someuser