# 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