python - Twisted 聊天客户端只在发送消息后直接接收消息?

标签 python client chat twisted server

我正在使用 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()

最佳答案

您的 sendData 正在阻塞。您可以将 Twisted 视为一个大的 while True 循环,它检查每个循环是否有事情要做。因此,一旦您进入 sendData 函数并调用 raw_input,您实际上就停止了整个程序。

看看this question

关于python - Twisted 聊天客户端只在发送消息后直接接收消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28216614/

相关文章:

python - 具有强制数据类型和维度的输入 numpy 数组的文档字符串格式

c - 如何从 Check Point 设备提取 Check Point 日志

javascript - 如何使用 crisp.chat RTM api?

javascript - 在 Firebase 中管理聊天 channel 的最佳方式

python - 在 Windows 操作系统中使用基于 Unix 的命令与 Anaconda

python - 如何构造嵌套的 numpy 记录数组?

python - 如何将http header 添加到使用scapy嗅探的数据包中

c++ - 与 Mule/ActiveMQ 和 C++ Stomp 的客户端通信

ssl - weblogic 作为 ssl 客户端(单边认证)

c# - 与多个客户端的C#TCP/IP简单聊天