Python3之socket粘包问题

tech2024-06-24  88

服务端

import socket import struct import subprocess phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) phone.bind(('127.0.0.1', 8080)) phone.listen(5) while 1: conn, addr = phone.accept() while 1: try: data = conn.recv(1024) res = subprocess.Popen(data.decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = res.stdout.read() stderr = res.stderr.read() # 发送报头 res = struct.pack('i', len(stdout) + len(stderr)) conn.send(res) # 发送数据部分 conn.send(stdout) conn.send(stderr) except Exception: break conn.close() phone.close()

客户端

from socket import * import subprocess ip = '' port = 8080 back_log = 5 buffer_size = 1024 tcp_server = socket(AF_INET, SOCK_STREAM) tcp_server.bind((ip, port)) tcp_server.listen(back_log) while True: conn, addr = tcp_server.accept() print('新的连接是', conn) print('新链接抵值', addr) while True: try: cmd = conn.recv(buffer_size) if not cmd: break res = subprocess.Popen(cmd.decode('utf-8'), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) err = res.stderr.read() if err: cmd_res = err else: cmd_res = res.stdout.read() length = len(cmd_res) conn.send(str(length).encode('gbk')) ready = conn.recv(buffer_size) if ready == b'ready': conn.send(cmd_res) except Exception as e: print(e) break conn.close() tcp_server.close()

参考文章:

Python3之socket粘包问题
最新回复(0)