我正在尝试使用Twisted框架编写服务器,并希望多次接收数据
class Echo(Protocol):
def connectionMade(self):
print " got connection from : " + str(self.transport.getPeer())
def dataReceived(self, data):
'''
get the client ip
'''
if(len(data)>40):
'''
initial setup message from the client
'''
client_details = str(self.transport.getPeer())#stores the client IP as a string
i = client_details.find('\'')#process the string to find the ip
client_details = client_details[i+1:]
j = client_details.find('\'')
client_ip = client_details[:j]
'''
Extract the port information from the obtained text
'''
data = data.split('@')
port1 = data[0]
port2 = data[1]
port3 = data[2]
if int(data) == 1:
method1(client_ip,port1)
if int(data) == 2:
method2(client_ip,port2)
我的问题:只有当来自客户端的消息中包含适当的整数数据时,才会调用method1和method2。有没有办法让我可以在客户端等待接收dataReceived()方法中的数据,或者我应该在dataReceived()方法本身中按顺序执行?
答案 0 :(得分:3)
收到某些数据时会调用dataReceived
方法。为了等待接收更多数据,您只需从dataReceived
返回,以便可以再次调用它。
此外,TCP不是基于消息的,而是基于流的。您的dataReceived
方法不能指望始终收到完整的消息,因此您的示例代码不正确。有关更多信息,请访问Twisted Matrix Labs网站上的See this frequently asked question。