python 用心跳(UDP包)探测不活动主机
计算机周期性的发送一个代表心跳的UDP包到服务器,服务器跟踪每台计算机在上次发送心跳之后尽力的时间并报告那些沉默时间太长的计算机。
客户端程序:HeartbeatClient.py
import timefrom twisted.application import internet, servicefrom twisted.internet import protocolfrom twisted.python import logUDP_PORT = 43278; CHECK_PERIOD = 20; CHECK_TIMEOUT = 15class Receiver(protocol.DatagramProtocol): """ Receive UDP packets and log them in the "client"s dictionary """ def datagramReceived(self, data, (ip, port)): if data == 'PyHB': self.callback(ip)class DetectorService(internet.TimerService): """ Detect clients not sending heartbeats for too long """ def _ _init_ _(self): internet.TimerService._ _init_ _(self, CHECK_PERIOD, self.detect) self.beats = { } def update(self, ip): self.beats[ip] = time.time( ) def detect(self): """ Log a list of clients with heartbeat older than CHECK_TIMEOUT """ limit = time.time( ) - CHECK_TIMEOUT silent = [ip for (ip, ipTime) in self.beats.items( ) if ipTime < limit] log.msg('Silent clients: %s' % silent)application = service.Application('Heartbeat')# define and link the silent clients' detector servicedetectorSvc = DetectorService( )detectorSvc.setServiceParent(application)# create an instance of the Receiver protocol, and give it the callbackreceiver = Receiver( )receiver.callback = detectorSvc.update# define and link the UDP server service, passing the receiver inudpServer = internet.UDPServer(UDP_PORT, receiver)udpServer.setServiceParent(application)# each service is started automatically by Twisted at launch timelog.msg('Asynchronous heartbeat server listening on port %d\n' 'press Ctrl-C to stop\n' % UDP_PORT)