daily notes[32]
Twisted网络框架使用Protocol类处理协议,每个连接创建临时实例,持久配置保存在Factory类中。示例代码展示了继承Protocol实现连接处理和数据回显,Factory类管理共享状态和协议实例创建。Protocol实例在连接结束后销毁,而Factory维护跨连接的配置信息。
·
文章目录
server
- Twisted usually using subclass
twisted.internet.protocol.Protocol
to treat protocols .Protocol is a fundamental class in Twisted for implementing network protocols. - protocol class instant don’t exists forever because of it will disappear from the memory of computer on demand,excluding any permanent configuration.
- 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()
- It’s best to define a subclass of Protocol class imported from
twisted.internet.protocol
in the first place.the subclass own theconnectionMade
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()
-
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()}")
- 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
- https://docs.twisted.org/
- deepseek
更多推荐
所有评论(0)