我正在使用Twisted框架编写一个简单的命令行聊天程序。在三个单独的命令行中,我打开了聊天服务器和两个客户端(请参阅下面的代码)。
我遇到的问题是,如果我从一个客户端发送消息,则下一个客户端将无法接收该消息。但是,一旦其他客户端发送自己的消息,它就会从另一个客户端收到消息。希望这很清楚。
由于
服务器:
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
data = repr(line)
print data
for c in self.factory.clients:
c.message(data)
def message(self, message):
self.transport.write(message + '\r\n')
from twisted.internet import reactor, protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
reactor.listenTCP(8042, factory)
reactor.run()
客户端:
from twisted.protocols import basic
# a client protocol
class EchoClient(basic.LineReceiver):
def sendData(self):
data = raw_input("> ")
if data:
print "sending %s...." % data
self.transport.write(data + "\r\n")
else:
self.transport.loseConnection()
def connectionMade(self):
self.username = raw_input("Name: ")
self.sendData()
def lineReceived(self, data):
print data
self.sendData()
def connectionLost(self, reason):
print "connection lost"
class EchoFactory(protocol.ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = EchoFactory()
reactor.connectTCP("localhost", 8042, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
答案 0 :(得分:1)
您的sendData正在阻止。您可以将Twisted视为一个大的while True
循环,它会检查每个循环是否有事情要做。因此,一旦您输入sendData函数并调用raw_input
,您实际上将停止整个程序。