第二十四天

今日内容

TCP协议套接字通信

一、解决粘包问题

  1.1:服务端
  from socket import *
  import subprocess
  import struct
  import json

  server = socket(AF_INET,SOCK_STREAM)
  server.bind(("127.0.0.1",8080))
  server.listen(5)
  while True:
      data,msg = server.accept()
      while True:
          try:
              res = data.recv(1024)
              if len(res) == 0:break
              obj = subprocess.Popen(res.decode("utf-8"),
                                     shell = True,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE
                                    )
              cmd1 = obj.stdout.read()
              cmd2 = obj.stderr.read()
              hander_dic = {
                  "name":"a.txt",
                  "total_size":len(cmd1+cmd2),
                  "md5":"12312312"
              }
              hander_json = json.dumps(hander_dic)
              hander_base = hander_json.encode("utf-8")
              data.send(struct.pack("i",len(hander_base)))
              data.send(hander_base)
              data.send(cmd1)
              data.send(cmd2)
          except Exception:
              break
      data.close()

  1.2客户端
  from socket import *
  import struct
  import json

  client = socket(AF_INET,SOCK_STREAM)
  client.connect(('127.0.0.1', 8080))

  while True:
      cmd = input(">>>: ").strip()
      if len(cmd) == 0:
          continue
      client.send(cmd.encode('utf-8'))

      # 先接收报头
      header = client.recv(4)
      header_base = struct.unpack('i', header)
      hander_dic_len = header_base[0]
      header_dic = client.recv(hander_dic_len)
      total_size = json.loads(header_dic.decode("utf-8"))["total_size"]
      # 再接收真正的数据
      recv_size = 0
      res = b''
      while recv_size < total_size:
          data = client.recv(1024)
          recv_size += len(data)
          res += data

      print(res.decode('gbk'))
posted @ 2021-01-18 20:03  抓鬼少年  阅读(39)  评论(0编辑  收藏  举报