1. 程式人生 > 實用技巧 >Python3 Socket與Socket心跳機制簡單實現

Python3 Socket與Socket心跳機制簡單實現

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'))#向服務端傳送訊息