粘包的完整处理 及tcp实现多连接方式
tcp_sever:
1 from socket import * 2 import os 3 import time 4 ip_prot = ('127.0.0.1',9000) 5 size = 1024 6 tcp_sever = socket(AF_INET,SOCK_STREAM) 7 tcp_sever.bind(ip_prot) 8 tcp_sever.listen(5) 9 10 while True: 11 12 conn,add = tcp_sever.accept() 13 while True: 14 try: 15 print('重新来一下') 16 data = conn.recv(size) 17 cmd_data = os.popen(data.decode('utf-8')).read() 18 19 20 if len(cmd_data)==0: 21 conn.send(str(len('您输入的命命令不存在'.encode('gbk'))).encode('gbk'))#注意这里面有个坑 cmd_data 要先转成bytes格式才计算长度 否则中文长度计算有问题 22 conn.send('您输入的命命令不存在'.encode('gbk')) 23 continue 24 conn.send(str(len(cmd_data.encode('gbk'))).encode('gbk')) #注意这里面有个坑 cmd_data 要先转成bytes格式才计算长度 否则中文长度计算有问题 25 time.sleep(0.5) 26 print('没发送') 27 conn.send(cmd_data.encode('gbk')) 28 print('发送完成') 29 except Exception as e: 30 print(e) 31 break 32 33 tcp_sever.close()
tcp _ client:
1 from socket import * 2 ip_prot = ('127.0.0.1',9000) 3 size = 1024 4 tcp_client = socket() 5 6 tcp_client.connect(ip_prot) 7 8 while True: 9 cmd = input('>>>') 10 tcp_client.send(bytes(cmd,encoding='utf-8')) 11 12 strsize =int(tcp_client.recv(size).decode('gbk')) #服务器返回需要接受字符串的长度 13 tot = 0 14 strfile = b'' 15 16 while tot != strsize: 17 18 print('长度为',strsize) 19 strfile += tcp_client.recv(size) 20 tot = len(strfile) 21 print('tot==>>>>>>>>>>>>>',tot) 22 print('正式的返回结果',strfile.decode('gbk')) 23 24 tcp_client.close()
client2:
1 from socket import * 2 ip_prot = ('127.0.0.1',9000) 3 size = 1024 4 tcp_client = socket() 5 6 tcp_client.connect(ip_prot) 7 8 while True: 9 cmd = input('>>>') 10 tcp_client.send(bytes(cmd,encoding='utf-8')) 11 12 strsize =int(tcp_client.recv(size).decode('gbk')) #服务器返回需要接受字符串的长度 13 tot = 0 14 strfile = b'' 15 16 while tot != strsize: 17 18 print('长度为',strsize) 19 strfile += tcp_client.recv(size) 20 tot = len(strfile) 21 print('tot==>>>>>>>>>>>>>',tot) 22 print('正式的返回结果',strfile.decode('gbk')) 23 24 tcp_client.close()