socket粘包实例解决
程序员文章站
2022-03-31 22:45:10
server.py import socket import subprocess sk = socket.socket() sk.bind(('127.0.0.1', 8081)) sk.listen(5) while True: conn, addr = sk.accept() while Tr ......
server.py
import socket
import subprocess
sk = socket.socket()
sk.bind(('127.0.0.1', 8081))
sk.listen(5)
while True:
conn, addr = sk.accept()
while True:
try:
recv_data = conn.recv(1024) if len(recv_data) == 0:break p = subprocess.Popen(str(recv_data, encoding='utf8'), shell=True, stdout=subprocess.PIPE) res = p.stdout.read() if len(res) == 0: send_data = 'cmd_err' else: send_data = str(res, encoding='gbk') send_data = bytes(send_data, encoding='utf8') ready_tag = 'Ready|%s' % len(send_data) conn.send(bytes(ready_tag, encoding='utf8')) feedback = conn.recv(1024) feedback = str(feedback, encoding='utf8') if feedback.startswith('Start'): conn.send(send_data) except Exception: break conn.close()
client.py
import socket
cli = socket.socket()
cli.connect(('127.0.0.1', 8081))
while True:
send_data = input('>>:').strip() if send_data == 'exit':break if len(send_data) == 0:continue cli.send(bytes(send_data, encoding='utf-8')) ready_tag = cli.recv(1024) ready_tag = str(ready_tag, encoding='utf-8') if ready_tag.startswith('Ready'): msg_size = int(ready_tag.split('|')[-1]) start_tag = 'Start' cli.send(bytes(start_tag, encoding='utf8')) recv_size = 0 recv_msg = b'' while recv_size<msg_size: recv_data = cli.recv(1024) recv_msg += recv_data recv_size += len(recv_data) print('MSG SIZE %s RECE SIZE %s' % (msg_size, recv_size)) print(str(recv_msg, encoding='utf8'))
cli.close()