我是新的扭曲,并阅读了许多相关的帖子,类似的问题,我有。然而,我无法推断以前的答案来解决我的简单问题。我确实参考了Twisted的FAQ部分,我还是搞不懂。在
我的问题是我有一个服务器在监听一个端口,当我收到一个“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()
在这里,您将
^{pr2}$self.otherFact.protocol
设置为EchoClient
类。在在这里,您将
EchoClient
类添加到self.factory.clients
列表中。这只会导致self.factory.clients
一次又一次充满了EchoClient
类的列表。在这里您尝试写入
EchoClient.transport
,它通常是None
,因为只有协议类的实例连接到传输,而不是类本身。在请尝试将连接的实例添加到
self.factory.clients
。我想,您正在设法创建这样的实例,因为您在FakeTelnet.connectionMade
中也有这样一行:但是,您并没有做任何将连接的协议放入
self.factory.clients
列表的操作。也许您可以这样定义self.otherFact
来代替:您还需要在某个时刻从
clients
列表中删除的内容。可能在协议的connectionLost
回调中:最后,如果您正在处理面向行的数据,您可能希望使用
twisted.protocols.basic.LineOnlyReceiver
作为FakeTelnet
的基类,并将您的逻辑放入其lineReceived
回调函数中。dataReceived
回调不保证数据边界,因此您可能永远看不到包含"START"
的单个字符串。例如,您可能得到两个对dataReceived
的调用,一个使用"ST"
,另一个使用"ART"
。在相关问题 更多 >
编程相关推荐