簡體   English   中英

Python Twisted DatagramProtocol UDP客戶端重新連接

[英]Python Twisted DatagramProtocol UDP Client Reconnect

鑒於我已經用DatagramProtocol在Twisted中實現了UDP客戶端,並使用它與UDP服務器通信,該服務器在一時會脫機(由於重新啟動-因此它不會更改其IP地址),請在我的協議中使用stopProtocol被調用,但是傳輸本身被Twisted設置為None。

如何解決Twisted中的簡單重新連接或重新啟動傳輸的問題? 根據文檔,我無法再次與udp連接。

鑒於在UDP中發送器即使在服務器死機后也應該能夠發送數據包,並且鑒於該協議在數據包中具有其自己的連接處理能力,因此,如果傳輸方式不可行,我可以完全在數據包層上重新連接邏輯部分消失。

我想在內核運行時用新協議再次運行listenUDP無效。

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor


class UDPClientProtocol(DatagramProtocol):
    def __init__(self, host, port):
       self.host = host
       self.port = port

    def startProtocol(self):
       # Called when transport is connected
       self.transport.connect(self.host, self.port)
       self.transport.write('initiate protocol') # pseudo code.

    def stopProtocol(self):
       print "I have lost connection and self.transport is gone!"
       # wait some time and try to reconnect somehow?

 t = reactor.listenUDP(0, UDPClientProtocol('127.0.0.1', 12345))
 reactor.run()

我使用了在Twisted DNS源文件中看到的以下技術。 它可以承受服務器斷開連接甚至網絡故障的影響。

from twisted.internet import reactor, protocol, task
import time

class EchoClientDatagramProtocol(protocol.DatagramProtocol):
    def __init__(self, host, port, reactor):
        self.host = host
        self.port = port
        self._reactor = reactor

    def startProtocol(self):
        self.transport.connect(self.host, self.port)

    def stopProtocol(self):
        #on disconnect
        self._reactor.listenUDP(0, self)

    def sendDatagram(self):
        datagram = ntp_packet
        try:
            self.transport.write(datagram, (self.host, self.port))
            print "{:0.6f}".format(time.time())
        except:
            pass

    def datagramReceived(self, datagram, host):
        pass
        #print 'Datagram received: ', repr(datagram)
        #self.sendDatagram()

def main():
    protocol = EchoClientDatagramProtocol('127.0.0.1', 8000, reactor)
    t = reactor.listenUDP(0, protocol)
    l = task.LoopingCall(protocol.sendDatagram)
    l.start(1.0) # call every second
    reactor.run()

if __name__ == '__main__':
    main()

有趣。 這聽起來像是不應該發生的事情。 這是由於網絡接口重啟還是其他原因? 什么條件再現了這一點?

對於您的問題的簡單答案可能是“使用'self'再次調用listenUDP ”,但我很好奇究竟是什么會導致此錯誤首先發生。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM