Python dataReceived()内的扭曲接收数据
我正在尝试使用Twisted framework编写一个服务器,希望多次接收数据Python dataReceived()内的扭曲接收数据,python,twisted,Python,Twisted,我正在尝试使用Twisted framework编写一个服务器,希望多次接收数据 class Echo(Protocol): def connectionMade(self): print " got connection from : " + str(self.transport.getPeer()) def dataReceived(self, data): ''' get the client ip '''
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()方法本身中按顺序接收数据?当接收到一些数据时,会调用
dataReceived
方法。为了等待更多的数据被接收,您只需要从dataReceived
返回,这样就可以再次调用它
此外,TCP不是基于消息的,而是基于流的。您的
dataReceived
方法不能指望总是收到完整的消息,因此您的示例代码不正确。更多信息,请访问Twisted Matrix Labs网站。那么,数据的顺序是否会被保留,变量是否会被设置,以便用于进一步传入的消息?我还没有试过那样做,但我现在要测试一下。从技术上讲,“变量”(设置为x=1
)不会是;“属性”(如self.x=1
)将被设置。但这是Python的一个基本问题,与Twisted无关。当您说,dataReceived不能指望总是收到完整的消息时,
,这就引发了另一个疑问,如果有多个客户端同时连接,客户端发送的消息将被视为单个流还是不同的流?如果连接了多个客户端,则会在工厂调用buildProtocol
,为每个连接创建一个新的Echo
实例。该实例将只接收该客户端的消息。