我有以下代码:
# 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
?
记住,这是客户端向服务器发送内容的持久连接,然后服务器处理它并向客户端发送内容。客户端再次向服务器发送内容,服务器处理并发送给客户端...(重复)
答案 0 :(得分:1)
def connectionMade(self):
# Asks user for their name
name = input('What is your name?')
# sends name to server
self.transport.write(name)
这将是每个客户端/连接的特定内容,因此您应该只有一个connectionMade方法。