最近在学习Twisted,基于Twisted框架实现了一个代理服务器。定义了两个协议:Client2Proxy用于客户端到代理服务器的通信,Proxy2Server用于代理服务器到目标服务器的通信。ProxyFactory是代理服务器的工厂类,用于创建代理服务器实例。当客户端连接时,它会暂停数据传输并连接到代理服务器,然后设置协议。当接收到数据时,它会打印十六进制数据并将数据转发给相应的服务器。
其实,在twisted.protocols下也给出了一个官方源码的实现,可以看该路径下的portforward.py参考,后面也贴Twisted的源码出来一并参考。
from twisted.internet import reactor,protocol
# 定义客户端到代理服务器的协议
class Client2Proxy(protocol.Protocol):
# 当接收到数据时,打印客户端发送的十六进制数据,并将数据转发给服务器
def dataReceived(self, data):
print(f'【客户端】【{self.transport.sessionno}】:{data.hex(" ").upper()}')
self.proxy2server.transport.write(data)
# 当建立连接时,暂停数据传输,并设置代理到服务器的协议
def connectionMade(self):
self.transport.pauseProducing()
client = protocol.ClientCreator(reactor, Proxy2Server)
client.connectTCP(host=self.factory.host, port=self.factory.port).addCallback(self.set_protocol)
# 当连接丢失时,打印客户端离开的消息,从代理列表中移除客户端,并关闭连接
def connectionLost(self, reason):
print(f'【客户端】【{self.transport.sessionno}】:离开')
self.factory.proxys.pop(self.transport.sessionno)
self.proxy2server.transport.loseConnection()
self.transport.loseConnection()
# 设置代理到服务器的协议
def set_protocol(self, client):
self.proxy2server=client
self.factory.proxys[self.transport.sessionno] = self
client.set_protocol(self)
print(f"客户端数量:{len(self.factory.proxys)}")
# 定义代理服务器工厂
class ProxyFactory(protocol.Factory):
protocol = Client2Proxy
proxys={}
# 初始化方法
def __init__(self,host,port):
self.host=host
self.port=port
# 定义代理服务器到目标服务器的协议
class Proxy2Server(protocol.Protocol):
# 当接收到数据时,打印服务端发送的十六进制数据,并将数据转发给目标服务器
def dataReceived(self, data):
print(f'【服务端】【{self.server.transport.sessionno}】:{data.hex(" ").upper()}')
self.server.transport.write(data)
# 设置代理到目标服务器的协议
def set_protocol(self,server):
self.server=server
self.server.transport.resumeProducing()#我们已经知道要把数据发给谁了,所以开始读取数据!
# 创建代理服务器工厂实例
factory=ProxyFactory("127.0.0.1",8101)
# 监听8001端口,并运行反应器
reactor.listenTCP(8001,factory)
reactor.run()
twisted.protocols下的实现:
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
A simple port forwarder.
"""
# Twisted imports
from twisted.internet import protocol
from twisted.python import log
class Proxy(protocol.Protocol):
noisy = True
peer = None
def setPeer(self, peer):
self.peer = peer
def connectionLost(self, reason):
if self.peer is not None:
self.peer.transport.loseConnection()
self.peer = None
elif self.noisy:
log.msg(f"Unable to connect to peer: {reason}")
def dataReceived(self, data):
self.peer.transport.write(data)
class ProxyClient(Proxy):
def connectionMade(self):
self.peer.setPeer(self)
# Wire this and the peer transport together to enable
# flow control (this stops connections from filling
# this proxy memory when one side produces data at a
# higher rate than the other can consume).
self.transport.registerProducer(self.peer.transport, True)
self.peer.transport.registerProducer(self.transport, True)
# We're connected, everybody can read to their hearts content.
self.peer.transport.resumeProducing()
class ProxyClientFactory(protocol.ClientFactory):
protocol = ProxyClient
def setServer(self, server):
self.server = server
def buildProtocol(self, *args, **kw):
prot = protocol.ClientFactory.buildProtocol(self, *args, **kw)
prot.setPeer(self.server)
return prot
def clientConnectionFailed(self, connector, reason):
self.server.transport.loseConnection()
class ProxyServer(Proxy):
clientProtocolFactory = ProxyClientFactory
reactor = None
def connectionMade(self):
# Don't read anything from the connecting client until we have
# somewhere to send it to.
self.transport.pauseProducing()
client = self.clientProtocolFactory()
client.setServer(self)
if self.reactor is None:
from twisted.internet import reactor
self.reactor = reactor
self.reactor.connectTCP(self.factory.host, self.factory.port, client)
class ProxyFactory(protocol.Factory):
"""
Factory for port forwarder.
"""
protocol = ProxyServer
def __init__(self, host, port):
self.host = host
self.port = port