我刚接触Twisted,读了很多类似于我遇到的问题的帖子。然而,我无法引申先前的答案来解决我的简单问题。我确实参考了Twisted的FAQ部分,但仍然不理解。
我的问题是,我有一个服务器在一个端口监听,并且当我收到“START”命令时,我想与几个客户端通信。例如,我使用一个单一的客户端,提供给我一个幸运饼干。但是,我无法从服务器代码中与客户端交流。请告诉我我哪里出错了?以下是代码:
我的问题是,我有一个服务器在一个端口监听,并且当我收到“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()