I have a basic TCP server implemented in twisted, to which a client is connected. The client connects and sends data necessary to start a websocket resource. Using these details sent by the TCP client, I want to add an autobahn websocket resource as a child under a twisted web resource. and when the client disconnects, I want to remove this child from the twisted web resource. please suggest, what should be the best way to implement this? Can I use resource.delEntity(child)?
so far, the code looks like this:
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)