Twisted study notes[1]

文章目录

server

  1. Twisted usually using subclass twisted.internet.protocol.Protocol to treat protocols .Protocol is a fundamental class in Twisted for implementing network protocols.
  2. protocol class instant don't exists forever because of it will disappear from the memory of computer on demand,excluding any permanent configuration.
  3. 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.
python 复制代码
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

  1. https://docs.twisted.org/
  2. deepseek