我需要的是一种中间人的实现:我需要一个服务器从客户端(不同长度的二进制数据)接收连接并将流转发到它连接的服务器(充当客户端),然后将数据从连接的服务器发送回客户端。
它实际上在客户端和服务器之间起作用,并且传递它们交换的数据(这是一个流,因此它不断地从一边传送到另一边)。
服务器是静态的,所以它总是一样的,它的地址甚至可以被硬编码;但是,当客户端断开连接时,该服务器还必须断开与“真实”服务器的连接。
我一直在环顾四周,但无法找到一个解决方案或例如这样一个简单的问题。
我所做的代码实际上工作正常,但我还没有成功找到如何在服务器部分中添加引用“这是您分配的客户端”的引用,或者引入到“这是您的服务器”。这里是我的代码:
蟒蛇扭曲的中间人执行
#!/usr/bin/env python
from twisted.internet import protocol, reactor
from twisted.protocols import basic
client = None
server = None
class ServerProtocol(protocol.Protocol):
def connectionMade(self):
global server
factory = protocol.ClientFactory()
factory.protocol = ClientProtocol
server = self
reactor.connectTCP('localhost', 1324, factory)
def dataReceived(self, data):
global client
client.transport.write(data)
class ClientProtocol(protocol.Protocol):
def connectionMade(self):
global client
# Here's the instance of the client
client = self
def dataReceived(self, data):
global server
server.transport.write(data)
def main():
import sys
from twisted.python import log
log.startLogging(sys.stdout)
factory = protocol.ServerFactory()
factory.protocol = ServerProtocol
# Here's the instance of the server
server = ServerProtocol
reactor.listenTCP(2593, factory)
reactor.run()
if __name__ == '__main__':
main()
现在,一点就是实例不能被包含到全局对象,并且应该把这两个类中:怎么了?
是的,我已经想通了,这样的事情可能是处理它的方式,但我宁愿不与构造玩,并添加到客户工厂的引用。这种方式很容易工作。 然后,关于从客户端到服务器的引用,我已经添加了一个对象到客户端,在客户端添加自己的对象之前是“None”。但是,我的代码在我的答案。现在我只需要在两种实现之间进行选择,你或我的! :) 谢谢你的帮助! – 2013-03-26 18:46:04