从 Twisted 服务器接收消息延迟

Lag in receiving messages from Twisted server

我有一个非常简单的客户端和服务器(都是用 Python 使用 Twisted 编写的)。服务器循环并每隔 X 毫秒向客户端发送一条消息。服务器 运行ning 在我的 Raspberry Pi 上,我的客户端在我的笔记本电脑上,两者都连接到我的家庭网络。

服务器:

from twisted.internet import reactor, protocol
from twisted.protocols.basic import NetstringReceiver
from twisted.internet.task import LoopingCall
from datetime import datetime

class MyProtocol(NetstringReceiver):

    def connectionMade(self):
        self.factory.myOnlyProtocol = self

    def connectionLost(self, reason):
        self.factory.myOnlyProtocol = None

class MyFactory(protocol.ServerFactory):

    protocol = MyProtocol

    def __init__(self):
        self.myOnlyProtocol = None
        self.timeStart = datetime.now()
        self.loop = LoopingCall(self.sendSomethingToClient)
        self.loop.start(0.1)
        print 'Server running'

    def sendSomethingToClient(self):
        if self.myOnlyProtocol is not None:
            millis = (datetime.now() - self.timeStart).microseconds / 1000
            print 'Since message sent: {}ms'.format(millis)
            self.timeStart = datetime.now()
            self.myOnlyProtocol.sendString('something')

reactor.listenTCP(1079, MyFactory())
reactor.run()

客户:

from twisted.internet import reactor, protocol
from twisted.protocols.basic import NetstringReceiver
from datetime import datetime

class MyProtocol(NetstringReceiver):

    def __init__(self):
        self.timeStart = datetime.now()

    def connectionMade(self):
        print 'Connected to server'

    def stringReceived(self, data):
        millis = (datetime.now() - self.timeStart).microseconds / 1000
        print 'Since last message: {}ms'.format(millis)
        self.timeStart = datetime.now()


class MyFactory(protocol.ClientFactory):

    protocol = MyProtocol


reactor.connectTCP('192.168.0.7', 1079, MyFactory())
reactor.run()

在我开始每 100 毫秒左右发送一次消息之前,这一切正常,此时客户端开始更零星地接收消息。这是我在 运行 脚本时看到的:

服务器:

Since message sent: 99ms
Since message sent: 99ms
Since message sent: 99ms
Since message sent: 99ms
Since message sent: 99ms
Since message sent: 99ms

客户端(每 1 毫秒消息):

Since last message: 181ms
Since last message: 0ms
Since last message: 147ms
Since last message: 0ms
Since last message: 188ms
Since last message: 1ms

如果我尝试更快地发送消息,只会加剧问题:

客户端(每 0.5 毫秒消息):

Since last message: 157ms
Since last message: 0ms
Since last message: 0ms
Since last message: 1ms
Since last message: 154ms
Since last message: 0ms
Since last message: 0ms
Since last message: 0ms 

我不确定 Twisted 发送消息是否有些奇怪,或者它是否是我的家庭网络,或者如何检查它是哪个。有什么想法吗?

当您关心 TCP 连接上的写入到读取延迟时,您的第一步应该是在客户端和服务器的 connectionMade 方法中禁用 Nagle's algorithm by doing self.transport.setTcpNoDelay(True)

如果您想衡量它是您的网络连接还是 Twisted,请仔细查看在客户端和服务器上收集的 Wireshark 日志并将它们与您的进程日志进行比较应该让您了解实际发送和接收流量的时间与应用层处理流量的时间。

如果您非常关心延迟,LoopingCall.withCount 会让您更好地了解是否有其他因素阻塞了主循环并导致计时器本身的测量不准确。