【发布时间】:2015-02-17 08:21:18
【问题描述】:
我正在尝试使用 Python 的扭曲框架编写 TCP 代理。我从 Twisted 的端口转发示例开始,它似乎在标准的 secnario 中完成了这项工作。问题是我有一个相当特殊的场景。我们需要做的是处理每个 TCP 数据包并寻找某种模式。
如果模式匹配我们需要做一个特定的过程。这个过程需要 30-40 秒(我知道这不是一个好的设计,但目前情况就是这样)。问题是,如果这个过程开始,所有其他数据包都会被阻止/卡住,直到过程完成。因此,如果有 100 个实时连接,即使其中 1 个调用该进程,所有剩余的 99 个进程都会卡住。
是否有一种标准的“扭曲”方式,其中每个连接/会话都在单独的线程中处理,以便“阻塞进程”不会干预其他实时连接?
示例代码:
from twisted.internet import reactor
from twisted.protocols import portforward
from twisted.internet import threads
def processingOperation(data)
# doing the processing operation here
sleep(30)
return data
def server_dataReceived(self, data):
if data.find("pattern we need to test")<> -1:
data = processingOperation(data)
portforward.Proxy.dataReceived(self, data)
portforward.ProxyServer.dataReceived = server_dataReceived
def client_dataReceived(self, data):
portforward.Proxy.dataReceived(self, data)
portforward.ProxyClient.dataReceived = client_dataReceived
reactor.listenTCP(8383, portforward.ProxyFactory('xxx.yyy.uuu.iii', 80))
reactor.run()
【问题讨论】: