最近在写公司的项目需要使用UDP 实现一个保活,而且需要用python 写,苦苦查找后,原来已经有大神完成了,就再次保存一下,防止以后忘记。

本文原:点击打开链接

""" 心跳客户端,周期性的发送 UDP包 """import socket, timeSERVER_IP = '192.168.0.15'; SERVER_PORT = 43278; BEAT_PERIOD = 5print 'Sending heartbeat to IP %s , port %d' % (SERVER_IP, SERVER_PORT)print 'press Ctrl-C to stop'while True:hbSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)hbSocket.sendto('PyHB', (SERVER_IP, SERVER_PORT))if _ _debug_ _:print 'Time: %s' % time.ctime( )time.sleep(BEAT_PERIOD)

""" 多线程 heartbeat 服务器""" import socket, threading, time UDP_PORT = 43278; CHECK_PERIOD = 20; CHECK_TIMEOUT = 15 class Heartbeats(dict):""" Manage shared heartbeats dictionary with thread locking """def _ _init_ _(self):super(Heartbeats, self)._ _init_ _( )self._lock = threading.Lock( )def _ _setitem_ _(self, key, value):""" Create or update the dictionary entry for a client """self._lock.acquire( )try:super(Heartbeats, self)._ _setitem_ _(key, value)finally:self._lock.release( )def getSilent(self):""" Return a list of clients with heartbeat older than CHECK_TIMEOUT """limit = time.time( ) - CHECK_TIMEOUTself._lock.acquire( )try:silent = [ip for (ip, ipTime) in self.items( ) if ipTime < limit]finally:self._lock.release( )return silent class Receiver(threading.Thread):""" Receive UDP packets and log them in the heartbeats dictionary """def _ _init_ _(self, goOnEvent, heartbeats):super(Receiver, self)._ _init_ _( )self.goOnEvent = goOnEventself.heartbeats = heartbeatsself.recSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)self.recSocket.settimeout(CHECK_TIMEOUT)self.recSocket.bind(('', UDP_PORT))def run(self):while self.goOnEvent.isSet( ):try:data, addr = self.recSocket.recvfrom(5)if data == 'PyHB':self.heartbeats[addr[0]] = time.time( )except socket.timeout:pass def main(num_receivers=3):receiverEvent = threading.Event( )receiverEvent.set( )heartbeats = Heartbeats( )receivers = [ ]for i in range(num_receivers):receiver = Receiver(goOnEvent=receiverEvent, heartbeats=heartbeats)receiver.start( )receivers.append(receiver)print 'Threaded heartbeat server listening on port %d' % UDP_PORTprint 'press Ctrl-C to stop'try:while True:silent = heartbeats.getSilent( )print 'Silent clients: %s' % silenttime.sleep(CHECK_PERIOD)except KeyboardInterrupt:print 'Exiting, please wait...'receiverEvent.clear( )for receiver in receivers:receiver.join( )print 'Finished.' if _ _name_ _ == '_ _main_ _':main( )

服务器程序接受ing跟踪“心跳”,她运行的计算机的地址必须和“客户端”程序中的 SERVER_IP一致。服务器必须支持并发,因为来自不同的计算机的心跳可能会同时到达。一个服务器有两种方法支持并发:多线程和异步操作。下面是一个多线程的ThreadbearServer.py,只使用了python标准库中的模块:

import time from twisted.application import internet, service from twisted.internet import protocol from twisted.python import log UDP_PORT = 43278; CHECK_PERIOD = 20; CHECK_TIMEOUT = 15 class 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_TIMEOUTsilent = [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 service detectorSvc = DetectorService( ) detectorSvc.setServiceParent(application) # create an instance of the Receiver protocol, and give it the callback receiver = Receiver( ) receiver.callback = detectorSvc.update # define and link the UDP server service, passing the receiver in udpServer = internet.UDPServer(UDP_PORT, receiver) udpServer.setServiceParent(application) # each service is started automatically by Twisted at launch time log.msg('Asynchronous heartbeat server listening on port %d\n''press Ctrl-C to stop\n' % UDP_PORT)

UDP 保活 python相关推荐

  1. python监听udp端口,Python和UDP监听

    我有一个应用程序,软件定义无线电,在一个端口上广播UDP数据包,告诉听众已经设置了什么频率和解调模式(等等). 我编写了一个演示python客户端(下面的代码)来监听端口,并将相应数据包中的信息转储到 ...

  2. php的udp数据传输,python实现udp数据报传输的方法

    waiting on port: 8081 reciveed: hello world from ('127.0.0.1', 62644) 补充: socket.sendto(string[, fla ...

  3. 网络编程的TCP和UDP实现(Python)

    socket包使用 缓冲区英文Buffer,因此缓冲区大小定义为BUF_SIZE TCP服务端: import socketip_port = ('127.0.0.1', 9000) BUF_SIZE ...

  4. python实现tcp发包_python 多线程tcp udp发包 Dos工具。

    现在肉鸡上面linux越来越多,都默认安装了python,有时候没有工具的时候可以自己写一个: 下面是支持 tcp和udp的python的发包代码: import socket,sys,threadi ...

  5. python共享内存通信mapofview_python map eval strPython socket模块实现的udp通信功能示例...

    本文实例讲述了Python socket模块实现的udp通信功能.分享给大家供大家参考,具体如下: socket介绍 socket(简称 套接字) 是进程间通信的一种方式,它与其他进程间通信的一个主要 ...

  6. python socket发包_python 多线程tcp udp发包 Dos工具。

    [使用 异步多线程TCP Socket 实现进程间通信(VC 6.0 , BCB6.0调试通过)            进程间通信有很多种方式,比如说 Pipe,共享内存,DDE,Socket等,关于 ...

  7. python数据包分析_packet_analysis: 数据包分析工具

    功能 读取pcap包,打印详细的icmp/tcp/udp协议 读取pcap包或网络接口 1. 打印详细的tcp会话/udp报文数据,目前支持mysql/pgsql/smtp/ftp/redis/mon ...

  8. python可以用来编写计算机网络程序吗_计算机网络(基于python做的笔记 )

    计算机网络(UDP 和 TCP) 概述 为了让在不同的电脑上运行的软件,之间能够互相传递数据,就需要借助网络的功能 使用网络能够把多方链接在一起,然后可以进行数据传递 所谓的网络编程就是,让在不同的电 ...

  9. python学习服务器端socket建立

    C/S模式简介 Tcp通信模型 Udp通信模型 python标准库中的socket模块 用socket建立TCP服务器端 用socket建立UDP服务器端 socket TCP服务器端测试代码 #co ...

最新文章

  1. 关于 Notepad++ 崩溃之后正在编辑文件内容被清空的致命问题的补救措施
  2. 不越狱换壁纸_9 款优质、免费越狱插件
  3. java web 讲义_Java之品优购课程讲义
  4. 每天一道LeetCode-----找到给定数组中第三大的值
  5. C# 使用 DirectoryInfo 递归指定目录中的所有目录及文件
  6. scrapy学习笔记(二)进阶使用
  7. Qt工作笔记-setWindowFlags的巧妙使用(使用|、、~运算符)
  8. erlang 常用函数
  9. Linux内核与文件系统分析
  10. html文档utf8文档字节,HTML UTF-8 参考手册
  11. 奇迹MU服务端架设教程技术分享探究_奇迹架设技术_奇迹SF套装
  12. 注意力模型(Attention Model)
  13. php匹配正则的方法,PHP实现正则匹配操作的方法
  14. Linus ,扎克伯格,雷军等巨佬的办公桌
  15. 一个三维四翼混沌系统混沌吸引子——MATLAB实现
  16. html的网页主题标记是什么,html标记是什么
  17. trian和val结果相差很大。
  18. C语言例题:输入某年某月某日,判断这一天是这一年的第几天?
  19. 树莓派4B之声音传感器模块(python3)
  20. 程序员必看!2021最新京东Java面试题目附详细答案解析

热门文章

  1. 实验吧/隐写术/小苹果
  2. VB.NET连接SQL server数据库解决方案(转载+亲自实践)
  3. Web前端开发职业技术要求规划
  4. java从弃坑到web
  5. java 寻找最大素数
  6. 【笔记】常用影视剪辑手法
  7. 学习笔记——主机端口扫描(1)主机端口及端口扫描方法
  8. 【PowerBI/PBI】PBI DAX之CALCULATE,IF 和 Excel VBA之COUNTIFS
  9. Mongo db 简单介绍及命令笔记
  10. 解决无法显示所有文件和文件夹,无法显示隐藏文件和文件夹