<p>你的问题不在于twisted,而在于python。阅读此常见问题条目:</p>
<blockquote>
<p><a href="http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#HowdoImakeinputononeconnectionresultinoutputonanother" rel="noreferrer"><em>How do I make input on one connection result in output on another?</em></a></p>
</blockquote>
<p>问题是,如果您想在串行连接协议中向TCP连接的客户端发送数据,只需向协议传递一个对工厂的引用,这样您就可以使用该引用来建立桥接。</p>
<p>下面是一些大致实现此目的的示例代码:</p>
<pre><code>class USBClient(Protocol):
def __init__(self, network):
self.network = network
def dataReceived(self, data):
print "Data received", repr(data)
#check & perhaps modify response and return to client
self.network.notifyAll(data)
#...
class CommandRx(Protocol):
def connectionMade(self):
self.factory.client_list.append(self)
def connectionLost(self, reason):
if self in self.factory.client_list:
self.factory.client_list.remove(self)
class CommandRxFactory(Factory):
protocol = CommandRx
def __init__(self):
self.client_list = []
def notifyAll(self, data):
for cli in self.client_list:
cli.transport.write(data)
</code></pre>
<p>初始化时,传递引用:</p>
<pre><code>tcpfactory = CommandRxFactory()
reactor.listenTCP(8000, tcpfactory)
SerialPort(USBClient(tcpfactory), 'COM8', reactor, baudrate='19200')
reactor.run()
</code></pre>