关于socket客户端接收不定长数据的解决方案
#!/usr/bin/env python3.5 # -*-coding:utf8-*- """ 本实例客户端用于不断接收不定长数据,存储到变量res """ import socket,time ip_port = ('192.168.1.189',1888) sk = socket.socket() sk.connect(ip_port) sk.setblocking(0) # 非阻塞模式,当接收没有发现任何数据时出异常 while True: user_input=input("cmd>>:").strip() if len(user_input) ==0:continue if user_input =="q":break sk.send(bytes(user_input,'utf8')) res = "" while True: try: time.sleep(0.1) server_replay = sk.recv(8000) res += str(server_replay,"utf8") except BlockingIOError: break print(res) res = "" sk.close()