permanent data

  1. the persistent data can be saved in the subclass of Factory .
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor

class MyProtocol(Protocol):
    def __init__(self, factory):
        self.factory = factory
    def connectionMade(self,factory):
        # Called when a new client connects
        self.factory.numProtocols=self.factory.numProtocols+1
        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
        self.factory.numProtocols=self.factory.numProtocols-1
        print(f"Client disconnected. Reason: {reason.getErrorMessage()}")

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

# Start the server on port 8000
reactor.listenTCP(8000, MyFactory())
print("Server running on port 8000...")
reactor.run()
  1. numProtocols survives in the instance of MyFactory .

  2. The buildProtocol method of the Factory while it meet every comming connection.

  3. The connectionLost function will be callied when any connection-specific objects was disconnect.

  4. to call loseConnection without worrying about transport writes being lost ,when you need to close a connection.loseConnection() is the preferred method - it performs a clean shutdown by:

    • Writing any pending data

    • Closing the connection only after all data is sent

    • Properly terminating the connection

from twisted.internet import protocol

class MyProtocol(protocol.Protocol):
    def connectionMade(self):
        print("Connection made")
        
    def loseConnection(self):
        # This is the proper way to close the connection
        self.transport.loseConnection()
        
    def connectionLost(self, reason):
        print("Connection lost:", reason)

For immediate termination (not recommended normally), use abortConnection():

transport.abortConnection()
  1. TCP4ServerEndpoint Implements TCP server endpoint with an IPv4 configuration
endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(QOTDFactory())
reactor.run()

reactor.run() launch the reactor,waits forever for connections to arrive on the port.through reactor.stop() ,you can stop the reactor .

references.

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

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

更多推荐