{{cd2>连接的客户端{1}要将消息发送到^外部的cd1}方法。我使用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')
出现此错误:
^{pr2}$如果我试图注释掉connection.send('test')
行,则会发生以下错误:
TypeError: 'NoneType' object is not iterable
我的代码有什么问题?在
我这样做对吗?或者有没有其他方法可以从协议类之外向客户机发送消息?在
谢谢。在
我这样做是为了传递信息。我使用
twisted
运行我的web应用程序。在我不知道这是否正确™,但对我来说效果很好。在
添加自工厂对于您的“init(self):”请参见以下内容:
相关问题 更多 >
编程相关推荐