1. 程式人生 > >struct模塊解決黏包問題

struct模塊解決黏包問題

code socket clas ESS conn span list struct模塊 err

client端執行命令

import socket
import subprocess
import struct

sk = socket.socket()
sk.connect((127.0.0.1,8080))
while True:
    cmd = sk.recv(1024).decode(gbk)
    if cmd ==q:
        break
    res = subprocess.Popen(cmd,shell=True,
                     stdout=subprocess.PIPE,
                     stderr
=subprocess.PIPE) stdout = res.stdout.read() stderr = res.stderr.read() length = len(stdout)+len(stderr) num_bytes = struct.pack(i,length) sk.send(num_bytes) sk.send(stdout) sk.send(stderr) sk.close()

server端發送命令

import socket
import struct
sk = socket.socket()
sk.bind((
127.0.0.1,8080)) sk.listen() conn,addr = sk.accept() while True: cmd = input(>>>) if cmd == q: conn.send(bq) break conn.send(cmd.encode(gbk)) num = conn.recv(4) num = struct.unpack(i,num)[0] res = conn.recv(int(num)).decode(gbk) print(res) conn.close() sk.close()

struct模塊解決黏包問題