Twisted study notes[2]
文章目录
- permanent data
- references.
permanent data
- the persistent data can be saved in the subclass of Factory .
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactorclass MyProtocol(Protocol):def __init__(self, factory):self.factory = factorydef connectionMade(self,factory):# Called when a new client connectsself.factory.numProtocols=self.factory.numProtocols+1client_ip = self.transport.getPeer().hostprint(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 clientprint(f"Received: {data.decode().strip()}")self.transport.write(b"Echo: " + data)def connectionLost(self, reason):# Called when the connection is closedself.factory.numProtocols=self.factory.numProtocols-1print(f"Client disconnected. Reason: {reason.getErrorMessage()}")class MyFactory(Factory):numProtocols=0def buildProtocol(self, addr):return MyProtocol(self)# Start the server on port 8000
reactor.listenTCP(8000, MyFactory())
print("Server running on port 8000...")
reactor.run()
-
numProtocols survives in the instance of MyFactory .
-
The buildProtocol method of the Factory while it meet every comming connection.
-
The connectionLost function will be callied when any connection-specific objects was disconnect.
-
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 protocolclass MyProtocol(protocol.Protocol):def connectionMade(self):print("Connection made")def loseConnection(self):# This is the proper way to close the connectionself.transport.loseConnection()def connectionLost(self, reason):print("Connection lost:", reason)
For immediate termination (not recommended normally), use abortConnection():
transport.abortConnection()
- 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.
- https://docs.twisted.org/
- deepseek