【发布时间】:2011-07-22 16:28:46
【问题描述】:
我是 Twisted 的新手,并且已经阅读了许多与我遇到的问题类似的相关帖子。但是,我无法推断以前的答案来解决我的简单问题。我确实参考了 Twisted 的常见问题解答部分 - 我仍然无法弄清楚。
我的问题是我有一台服务器正在监听一个端口,当我收到“START”命令时,我想与多个客户端交谈。例如,我使用了一个客户端,它为我提供幸运饼干。但是,我无法在服务器代码中与客户端交谈。你能告诉我哪里出错了吗?代码如下:
from twisted.internet import reactor, protocol
from twisted.internet.protocol import Protocol, Factory
class FakeTelnet(Protocol):
def connectionMade(self):
print 'local connection made'
self.otherFact = protocol.ClientFactory()
self.otherFact.protocol = EchoClient
self.factory.clients.append(self.otherFact.protocol)
reactor.connectTCP('psrfb6',10999, self.otherFact)
def dataReceived(self, data):
if 'START' in data:
# send a command to cookie server.
for client in self.factory.clients:
client.transport.write('START\r\n')
def connectionLost(self):
print 'connection lost'
class EchoClient(Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
print "Connection to cookie server"
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Fortune Server said:", data
def connectionLost(self):
print "connection lost"
def send_stuff(data):
self.transport.write(data);
class MyFactory(Factory):
protocol = FakeTelnet
def __init__(self, EchoClient):
self.clients = []
self.otherCli = EchoClient
reactor.listenTCP(5823, MyFactory(EchoClient))
reactor.run()
【问题讨论】:
-
一个简短的更新:我检查了这个常见问题解答:twistedmatrix.com/trac/wiki/… - 但我仍然无法理解它。我想要的是使用在 FakeTelnet 中建立的客户端连接在 dataReceived 中可用。任何帮助将不胜感激。谢谢。