文章目录
server
- Twisted usually using subclass
twisted.internet.protocol.Protocol to treat protocols .Protocol is a fundamental class in Twisted for implementing network protocols.
- protocol class instant don't exists forever because of it will disappear from the memory of computer on demand,excluding any permanent configuration.
- the persistent configuration saves into Factory class inherited from
twisted.internet.protocol.Factory, The buildProtocol method in a Factory class was put in charge of creating a new instance of Protocol class for each incoming connection.
from twisted.internet.protocol import Factory, Protocol
class MyProtocol(Protocol):
def connectionMade(self):
peer = self.transport.getPeer()
print(f"New connection from {peer.host}:{peer.port}")
def dataReceived(self, data):
print(f"Received: {data.decode('utf-8')}")
self.transport.write(data) # Echo back
class MyFactory(Factory):
def __init__(self):
self.active_connections = 0 # Shared state across all protocols
def buildProtocol(self, addr):
self.active_connections += 1
print(f"Creating new protocol instance (Total connections: {self.active_connections})")
return MyProtocol()
references
- https://docs.twisted.org/
- deepseek