Python Twiested,在哪里读取客户端输入

Python Twiested, where to read client input

我有以下代码:

# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.


"""
An example client. Run simpleserv.py first before running this.
"""

from twisted.internet import reactor, protocol


# a client protocol

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

    def connectionMade(self):
        self.transport.write("Welcome to Calculator!")
        # data = ''

    def dataReceived(self, data):
        "As soon as any data is received, write it back."
        print "Server said:\n", data
        # self.transport.loseConnection()

    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 running on port 8000
def main():
    help(protocol.Protocol)
    exit()
    f = EchoFactory()
    reactor.connectTCP("localhost", 8000, f)
    reactor.run()

    print 'here'

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()

读取客户端输入并将其发送到服务器的正确方法是什么?我想使用 data = input() 读取数据,然后将其发送到服务器 self.transport.write(data)。但是,在我必须将它放在我的代码中的地方,我是否必须创建另一种方法或使用 connectionMade? 请记住,这是一个持久连接,客户端向服务器发送一些东西,然后服务器处理它并向客户端发送一些东西。然后客户端再次向服务器发送一些东西,服务器处理它并发送给客户端......(重复)

def connectionMade(self):
        # Asks user for their name
        name = input('What is your name?')
        # sends name to server
        self.transport.write(name)

这将特定于每个 client/connection,因此您应该只有一个连接 Made 方法。