twisted编写简单的web代理服务器

前几天一直在看关于Twisted方面编程的文章,今天小试一把。写了一个非常简单的web代理服务器,没有用到专门管理callback的deferred。只使用了最简单的Twisted网络编程。

首先需要创建一个监听用户请求的服务器端。创建相应的Factory和Protocol。

ProxyProtocol用于接受用户的HTTP请求。从HTTP报文中分析出用户想要链接的服务器端url,存放于url变量中。然后在与服务器建立链接。

class ProxyProtocol(Protocol):
	def __init__(self):
		self.host=''
		self.port=''
		self.request=''

	def connectionMade(self):
		#print 'connected from ',self.transport.getPeer().host
		self.host=self.transport.getPeer().host
		self.port=self.transport.getPeer().port

		print self.transport.getPeer()

	def dataReceived(self, data):
		self.request=data
		
		index1=self.request.index(' ');
		index2=self.request.index(' ',index1+1);
		if((index1==-1)or(index2==-1)):
			raise Exception('http url error')
		part1=self.request[index1+1:index2];

		index3=part1.index('/',8);
		
		url=part1[7:index3];

		print 'get the url: ',url
		print self.request

		factory=ProxyWebFactory(self.request,self)
		reactor.connectTCP(url,80,factory);
		#self.transport.loseConnection()

	def connectionLost(self, reason):
		pass

ProxyFactory用于创建和管理ProxyProtocol。这里直接继承,ServerFactory。

class ProxyFactory(ServerFactory):
	protocol=ProxyProtocol
	
	def __init__(_):
		pass

 之后需要建立一个向网站服务器发送请求和接受服务器送回的数据的Protocol以及相应的Factory。

ProxyWebProtocol将请求发送到web服务器。并接受服务器传回的数据。

class ProxyWebProtocol(Protocol):

	def __init__(self):
		self.request=''

	def connectionMade(self):
		self.transport.write(self.factory.request)
		self.factory.request=''
	
	def dataReceived(self, data):
		self.request=data
		self.factory.proxyprotocol.transport.write(self.request);
		self.request=''
		#self.transport.loseConnection()

	def connectionLost(self, reason):
		pass
ProxyWebFactory为相应的Factory
class ProxyWebFactory(ClientFactory):
	
	protocol=ProxyWebProtocol
	
	def __init__(self,data,pro):
		self.request=data;
		self.proxyprotocol=pro

	def clientConnectionFailed(self,connector,reason):
		pass	

之后,在main函数中调用即可。

	factory=ProxyFactory()

	port=reactor.listenTCP(8001,factory,True)
	
	print 'listening on ',port

	reactor.run()

此代理服务器有很多的不足,比如异常的处理,web服务器端口可能不是80,没有缓存等问题。

过几天再改进改进,尝试一下使用deferred。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值