5.twisted 端口转发服务器

泄露秘密 提交于 2020-02-12 09:28:41

一个简单的端口转发服务器:
#coding:utf8
__author__ = 'python'
from twisted.application.service import  Application,Service
from twisted.internet import  reactor,protocol
class Server(protocol.Protocol):
    def dataReceived(self, data):
        self.client.transport.write(data)
    def connectionMade(self):
        "暂停从transport读取任何数据,因为我们不知道收到数据后发给谁!"
        self.transport.pauseProducing()
        client=protocol.ClientCreator(reactor,Client)
        client.connectTCP(host="172.17.20.101",port=8500).addCallback(self.set_protocol)
    def connectionLost(self, reason):
        self.client.transport.loseConnection()
    def set_protocol(self,client):
        self.client=client
        client.set_protocol(self)
class Client(protocol.Protocol):
    def dataReceived(self, data):
        self.server.transport.write(data)
    def set_protocol(self,server):
        self.server=server
        self.server.transport.resumeProducing()#我们已经知道要把数据发给谁了,所以开始读取数据!
factory=protocol.ServerFactory()
factory.protocol=Server
reactor.listenTCP(8080,factory)
reactor.run()

效果如下:

成功转发到相应端口!

clipboard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!