Twisted在dataReceived()中接收数据

3 投票
1 回答
4905 浏览
提问于 2025-04-17 16:32

我正在尝试使用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()方法里顺序处理呢?

1 个回答

3

dataReceived 方法是在接收到一些数据时被调用的。为了等待更多数据的到来,你只需要在 dataReceived 方法中返回,这样它就可以再次被调用。

另外,TCP 不是基于消息的,而是基于流的。这意味着你的 dataReceived 方法不能指望每次都能收到完整的消息,所以你提供的示例代码是不正确的。想了解更多信息,可以查看 Twisted Matrix Labs 网站上的常见问题

撰写回答