python socket通信 心跳_Python Socket 多客户端心跳监测 | kTWO-个人博客

# 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值