【问题标题】:Twisted receiving data within dataReceived()dataReceived() 中的扭曲接收数据
【发布时间】:2013-02-20 19:33:00
【问题描述】:

我正在尝试使用 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() 方法本身中按顺序执行?

【问题讨论】:

    标签: python twisted


    【解决方案1】:

    当接收到一些数据时调用dataReceived 方法。为了等待接收更多数据,您只需从dataReceived返回,以便再次调用它。

    另外,TCP 不是基于消息的,它是基于流的。您的 dataReceived 方法不能指望始终收到完整的消息,因此您的示例代码不正确。 See this frequently asked question Twisted Matrix Labs 网站了解更多信息。

    【讨论】:

    • 那么是否会保留数据的顺序并设置变量以用于进一步传入的消息?我还没有尝试过这种方式,但我现在将对其进行测试。
    • 从技术上讲,“变量”(设置为x = 1)不会; “属性”(设置为self.x = 1)会。这是一个基本的 Python 问题,与 Twisted 无关。
    • 当你说dataReceived cannot count upon always receiving a complete message时,又引发了另一个疑问,如果有多个客户端同时连接,客户端发送的消息会被视为单个流还是不同?
    • 如果您连接了多个客户端,buildProtocol 将在您的工厂中调用,为每个连接创建一个新的Echo 实例。该实例将只接收该客户端的消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多