我如何接受用户输入以手动结束连接

时间:2019-03-12 15:35:25

标签: twisted

好吧!所以在这里,我在python中有一个客户端代码,可以连接到服务器并接受用户输入以与服务器进行通信,但是当我键入一条消息时,它会立即关闭连接...有没有办法可以让用户输入以手动终止连接?

from twisted.internet import reactor, protocol

global cntnt
cntnt = ''

class EchoClient(protocol.Protocol):
    """Once connected, send a message, then print the result."""

    def connectionMade(self):
        self.transport.write(raw_input("say something: "))

    def dataReceived(self, cntnt):
        "As soon as any data is received, write it back."
        print ("Server said:", cntnt)

        self.transport.loseConnection()

    def connectionLost(self, reason):
        print ("connection closed")

class EchoFactory(protocol.ClientFactory):
    protocol = EchoClient

    def clientConnectionFailed(self, connector, reason):
        print ("Connection failed - goodbye!")
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print ("Connection closed safely - goodbye!")
        reactor.stop()

def main():
    f = EchoFactory()
    reactor.connectTCP("localhost", 80, f)
    reactor.run()

if __name__ == '__main__':
    main()

0 个答案:

没有答案