<p>谢谢,开始工作了。无法让def notifyAll将数据发送到我的调制解调器..是这样的吗:客户端列表中的for cli:cli.transport.write(data)<br/>
新代码:</p>
<pre><code>import sys
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.internet.protocol import Protocol
from twisted.internet.serialport import SerialPort
from twisted.python import log
log.startLogging(sys.stdout)
client_list = []#TCP clients connecting to me
usb_list = []
class USBClient(Protocol):
def __init__(self, network):
self.network = network
self.usb_list = []
def connectionFailed(self):
print "Connection Failed:", self
reactor.stop()
def connectionMade(self):
usb_list.append(self)
print 'Connected to USB modem'
USBClient.sendLine(self, 'AT\r\n')
def dataReceived(self, data):
print "Data received", repr(data)
print "Data received! with %d bytes!" % len(data)
for cli in client_list:
cli.transport.write(data)
#self.network.notifyAll(data)# !!AArgh..!Could not get this to work
pass
def lineReceived(self, line):
print "Line received", repr(line)
def sendLine(self, cmd):
print cmd
self.transport.write(cmd + "\r\n")
def outReceived(self, data):
print "outReceived! with %d bytes!" % len(data)
self.data = self.data + data
class CommandRx(Protocol):
def connectionMade(self):
print 'Connection received from tcp..'
client_list.append(self)
def dataReceived(self, data):
print 'Command receive', repr(data)
for usb in usb_list:
usb.transport.write(data)
def connectionLost(self, reason):
print 'Connection lost', reason
if self in client_list:
print "Removing " + str(self)
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('yipee')
if __name__ == '__main__':
tcpfactory = CommandRxFactory()
reactor.listenTCP(8000, tcpfactory)
SerialPort(USBClient(tcpfactory), '/dev/ttyUSB4', reactor, baudrate='19200')
reactor.run()
</code></pre>