本文适Python分布式任务的心跳监测,客户端可自定义时间发送包到服务端,让客户端确定客户端的存在。使用的是短连接,支持单客户端多进程,但代码没有封装,只提供思路和方法,还请自行封装。
一、程序流程:
二、运行截图:
三、Server端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# coding:utf8 import socket import time import thread #接受心跳包 def get_hart(host, port): global clien_list s = socket.socket() s.bind((host, port)) s.listen(5) while True: try: clien, address = s.accept() try: clien_data = clien.recv(1024) if clien_data == str(0): clien_id = clien_reg() clien.send(str(clien_id)) #print clien_list else: clien_list[int(clien_data)]['time'] = time.time() #print clien_data except: print 'send fail!' clien.close() except: print "accept fail!" continue #客户端注册 def clien_reg(): global clien_list tim = str(time.time()/100).split('.') id=int(tim[1]) clien_list[id] = {"time":time.time(), "state":0} return id # 参数:客户机字典,延时 def check_hart(clien_list, delay, lost_time): while True: for id in clien_list: if abs(clien_list[id]['time'] - time.time()) > lost_time: clien_list[id]['state'] = 0 del clien_list[id] #删除断开的客户端 break #不跳会报错 else: clien_list[id]['state'] = 1 print clien_list time.sleep(delay) if __name__ == '__main__': host = '127.0.0.1' port = 8888 global clien_list #存储客户端信息的字典 clien_list={} lost_time = 30 #判断断开连接的超时时间 try: thread.start_new_thread(get_hart, (host, port, )) thread.start_new_thread(check_hart, (clien_list, 5, lost_time,)) except: print "thread error!" while 1: pass |
四、Clien端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# coding:utf8 import socket import time #发送心跳包 参数:主机ip,端口号,发包延时时间 def send_hart(host, port, delay): s = socket.socket() global clien_id try: s.connect((host, port)) s.sendall(str(clien_id)) if clien_id == 0: try: to_clien_id = s.recv(1024) clien_id = to_clien_id except: print 'send fail!' print to_clien_id #测试返回id time.sleep(delay) except: print 'connect fail!' time.sleep(delay) if __name__ == '__main__': host = '127.0.0.1' port = 8888 global clien_id clien_id = 0 #客户端注册id while True: send_hart(host, port, 5) |