Python解决TCP黏包问题

以控制命令行为例
struct模块可以将任意类型转换为一个固定长度的bytes
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(b'q')
      break
   conn.send(cmd.encode('gbk'))
   num = connrecv(4)
   num = struct.unpack('i',num)[0]
   res = conn.recv(int(num)).decode('gbk')
   print(res)
conn.close()
sk.close()

Client端

import socket
import struct
import subprocess
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)
   std_out = res.stdout.read()
   std_err = res.stderr.read()
   len_num = len(std_out) + len(std_err)
   num_by = struct.pack('i', len_num)
   sk.send(num_by)
   sk.send(std_out)
   sk.send(std_err)
sk.close()
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读