daily notes[30]
本文介绍了使用Twisted框架实现持久化数据存储的方法。通过在Factory子类中保存数据(如示例中的numProtocols变量),可实现跨连接共享数据。文章详细说明了连接建立(connectionMade)、数据接收(
permanent data
- 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()
-
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 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()
- 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
更多推荐
所有评论(0)