现在需要客户端和服务端通信,服务端主动给客户端发信息
服务端
import socket import time BUF_SIZE = 1024 host = '0.0.0.0' port = 9998 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((host, port)) server.listen(1) #接收的连接数 client, address = server.accept() #因为设置了接收连接数为1,所以不需要放在循环中接收 while True: #循环收发数据包,长连接 #data = client.recv(BUF_SIZE) #print(data.decode()) #python3 要使用decode client.send('keepalive\r\n'.encode()) time.sleep(60) # client.close() #连接不断开,长连接
客户端
import socket import datetime print(datetime.datetime.now()) host = 'barcode.ydqzj.cn' port = 9998 BUF_SIZE = 1024 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) #在客户端开启心跳维护 client.connect((host, port)) while True: #client.send('hello world\r\n'.encode()) #print('send data') data = client.recv(BUF_SIZE) print(data.decode()) #time.sleep(5) #如果想验证长时间没发数据,SOCKET连接会不会断开,则可以设置时间长一点