TCP套接字非阻塞示例:萌新学习笔记
程序代码:
import os,sys from socket import * from time import ctime,sleep # TCP套接字非阻塞示例 # 循环等待连接,当没有连接时,每隔10秒写入一行日志 fw = open('log.txt','a+',encoding='utf-8') # 以utf-8编码格式打开日志文件追加模式 sockfd = socket() sockfd.bind(('0.0.0.0',8888)) sockfd.listen(3) sockfd.setblocking(False) # 设置非阻塞 # sockfd.settimeout(3) #设置超时时间3秒 time_out = 0 print('Waiting for connect...') while True: # 尝试接收连接,返回套接字和地址 try: connfd, addr = sockfd.accept() # 当出现无连接和超时异常后 except (BlockingIOError,timeout) as e: sleep(0.1) # 延迟0.1秒 time_out += 1 if time_out > 100: # 每延迟10秒写一次日志 # 把错误信息写入日志文件 fw.write("%s : %s\n"%(ctime(),e)) fw.flush() # 刷新保存日志文件 time_out = 0 print('Waiting for connect...') else: wait_time = 0 print('no msg') while True: try: data = connfd.recv(1024) print(data) connfd.send(b'OK') wait_time = 0 except: sleep(0.1) # 无信息异常等待0.1秒 wait_time += 1 if wait_time > 100: # 当10秒无信息,则提示一次 print('no msg') wait_time = 0