[英]Lag in receiving messages from Twisted server
我有一個非常簡單的客戶端和服務器(都使用Twisted編寫的Python)。 服務器循環並每X毫秒向客戶端發送一條消息。 服務器在我的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()
這工作正常,直到我開始每100ms左右發送一次消息,此時客戶端開始偶爾開始接收消息。 這是我在運行腳本時看到的內容:
服務器:
Since message sent: 99ms
Since message sent: 99ms
Since message sent: 99ms
Since message sent: 99ms
Since message sent: 99ms
Since message sent: 99ms
客戶端(每1ms消息):
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.5ms發送一次消息):
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
方法中執行self.transport.setTcpNoDelay(True)
來禁用Nagle的算法 。
如果要測量它是網絡連接還是Twisted,請仔細查看在客戶端和服務器上收集的Wireshark日志,並將它們與流程日志進行比較,這樣可以讓您了解實際發送和接收流量的時間。當它由應用層處理時。
如果你非常關心延遲, LoopingCall.withCount
會讓你更好地了解其他東西是否阻塞了主循環並導致你的計時器本身的測量結果不准確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.