<p>我使用了在<a href="https://twistedmatrix.com/trac/browser/tags/releases/twisted-11.0.0/twisted/names/dns.py#L1752" rel="nofollow">Twisted DNS source file</a>上看到的以下技术。它能经受服务器断开连接甚至网络故障。在</p>
<pre><code>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()
</code></pre>