server
import socket import datetime s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind(('127.0.0.1',9999)) s.listen(1) starttime = None endtime = None def Wait_connection(): global starttime s.settimeout(None) conn,addr=s.accept() starttime = datetime.datetime.now() print('client addr',addr) client_msg=conn.recv(1024) print('client msg: %s' %(str(client_msg,'utf-8'))) keep_alive() def keep_alive(): global endtime a = 1 while a==1: try: s.settimeout(5) print('---------------------------------') conn,addr=s.accept() print('client addr',addr) client_msg=conn.recv(1024)#客户端发送过来的消息 print('client msg: %s' %(str(client_msg,'utf-8'))) except: a = 2 endtime = datetime.datetime.now() print('连接已断开,本次连接持续 %s 秒'%str((endtime - starttime).seconds)) Wait_connection() if __name__ == '__main__': Wait_connection()
client
import socket import time a = 0 while True: time.sleep(4) a+=1 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(('127.0.0.1',9999)) keepclass = "我已连接"+str(a*4)+"秒" s.send(bytes(keepclass,'UTF-8'))#向服务端发送消息