1

我有一个以扭曲方式实现的基本 TCP 服务器,客户端连接到该服务器。客户端连接并发送启动 websocket 资源所需的数据。使用 TCP 客户端发送的这些详细信息,我想在扭曲的 Web 资源下添加一个高速公路 websocket 资源作为子资源。当客户端断开连接时,我想从扭曲的网络资源中删除这个孩子。请提出建议,实现这一点的最佳方法应该是什么?我可以使用 resource.delEntity(child) 吗?

到目前为止,代码如下所示:

from twisted.internet.protocol import Protocol, Factory
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol
from autobahn.twisted.resource import WebSocketResource

class ProtoPS(WebSocketServerProtocol):
  def onMessage(self,payload,isBinary):
    if not isBinary:
        print("Text message received: {}".format(payload.decode('utf8')))
    self.sendMessage(payload,isBinary)

class BaseResource:
  def __init__(self,proto,vid):
    self.vid = vid
    self.factory = WebSocketServerFactory()
    self.factory.protocol = proto
    self.resource = WebSocketResource(self.factory)
    wsroot.putChild(self.vid,self.resource)

class BackendProto(Protocol):
  def __init__(self):
    self.SERVICEMAP = {}

  def dataReceived(self,data):
    msg = json.loads(data)
    if ('cmd' in msg) and (msg['cmd'] == "create"):
         self.vid = msg['client']['id']
         self.SERVICEMAP[self.vid] = BaseResource(ProtoPS,self.vid)

  def connectionLost(self,reason):
    wsroot.delEntity(self.vid)
    del self.SERVICEMAP[self.vid]

class BackendFactory(Factory):
  protocol = BackendProto

if __name__ == '__main__':
  reactor.listenTCP(8081,BackendFactory())
  wsroot = Data("","text/plain")
  wssite = Site(wsroot)
  reactor.listenTCP(9000,wssite)
4

0 回答 0