zoukankan      html  css  js  c++  java
  • 第二十四天

    今日内容

    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'))
  • 相关阅读:
    【ARTS】打卡第七周
    【ARTS】打卡第六周
    【ARTS】打卡第五周
    【leetcode】 438. Find All Anagrams in a String
    【ARTS】打卡第四周
    【ARTS】打卡第三周
    【leetcode】 11. Container With Most Water
    【ARTS】打卡第二周
    【ARTS】打卡第一周
    深度VS广度——谈谈对测试职业的一些思考
  • 原文地址:https://www.cnblogs.com/kk942260238/p/14294865.html
Copyright © 2011-2022 走看看