我有一个使用twisted
和autobahn
编写的websocket服务器。它是一个echo服务器,我想添加从多播UDP端口接收的消息转发到websocket服务器的客户端的功能。
我尝试了在tcp服务器中为完全相同的功能所做的事情,但这似乎不起作用。
class SomeServerProtocol(WebSocketServerProtocol):
def onOpen(self):
self.factory.register(self)
# Adding this line in TCP protocol's on connection method worked.
self.port = reactor.listenMulticast(6027, Listener(self), listenMultiple=True)
def connectionLost(self, reason):
self.factory.unregister(self)
def onMessage(self, payload, isBinary):
self.sendMessage(payload)
class PriceListener(DatagramProtocol):
def __init__(self, stream):
self.stream = stream
def startProtocol(self):
self.transport.setTTL(5)
self.transport.joinGroup("0.0.0.0")
def datagramReceived(self, datagram, address):
# Do some processing
# Send the data
class SomeServerFactory(WebSocketServerFactory):
def __init__(self, *args, **kwargs):
super(SomeServerFactory, self).__init__(*args, **kwargs)
self.clients = {}
def register(self, client):
self.clients[client.peer] = {"object": client, "id": k}
def unregister(self, client):
self.clients.pop(client.peer)
if __name__ == "__main__":
log.startLogging(sys.stdout)
# static file server seving index.html as root
root = File(".")
factory = SomeServerFactory(u"ws://127.0.0.1:8080")
factory.protocol = SomeServerProtocol
resource = WebSocketResource(factory)
# websockets resource on "/ws" path
root.putChild(u"ws", resource)
site = Site(root)
reactor.listenTCP(8080, site)
reactor.run()
我在SomeServerProtocol
标记了我添加的行,让它在UDP线上侦听。删除此行一切正常。我正在获取UDP线路上的数据,我想将UDP线路上的任何数据推送到连接到websocket服务器的所有客户端。
我已经检查过服务器是否正常工作,客户端是否能够连接。 我该怎么做呢?如果能够澄清为什么TCP解决方案在这里不起作用,那将是很好的。
PS
我在客户端遇到以下错误。
WebSocket connection to 'ws://localhost:8080/ws' failed: One or more reserved bits are on: reserved1 = 1, reserved2 = 0, reserved3 = 1
我对此问题有所了解here。那么在websocket协议中从多播接收数据会导致这种情况吗?