文章目录

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.
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()
  1. It’s best to define a subclass of Protocol class imported from twisted.internet.protocol in the first place.the subclass own the connectionMade function which is a callback method that is invoked when a new connection is established.
    def connectionMade(self):
        print("New connection established!")
        self.transport.write(b"Hello, client!\r\n")

And in the second place, the subclass of Factory Should be defined used to create a instance of the subclass of Protocol.

class MyFactory(Factory):
    def buildProtocol(self, addr):
        return MyProtocol()

In the end, you from need to use reactor which is imported from twisted.internet for starting Twisted’s event loop handling the asynchronous operations.

from twisted.internet import reactor
reactor.listenTCP(8000, MyFactory())
reactor.run()
  1. The connectionLost event will be triggered when a connection is closed or lost ,which could happen due to:

    The client disconnecting.

    An error occurring (e.g., network failure).

    The server actively closing the connection.

  def connectionLost(self, reason):
        # Called when the connection is closed
        print(f"Client disconnected. Reason: {reason.getErrorMessage()}")
  1. all code shown as follows.
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor

class MyProtocol(Protocol):
    def connectionMade(self):
        # Called when a new client connects
        client_ip = self.transport.getPeer().host
        print(f"New connection from: {client_ip}")
        self.transport.write(b"Welcome! Type something...\r\n")

    def dataReceived(self, data):
        # Called when data is received from the client
        print(f"Received: {data.decode().strip()}")
        self.transport.write(b"Echo: " + data)

    def connectionLost(self, reason):
        # Called when the connection is closed
        print(f"Client disconnected. Reason: {reason.getErrorMessage()}")

class MyFactory(Factory):
    def buildProtocol(self, addr):
        return MyProtocol()

# Start the server on port 8000
reactor.listenTCP(8000, MyFactory())
print("Server running on port 8000...")
reactor.run()

references

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

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐