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'))
  • 相关阅读:
    Java线程面试题 Top 50
    深入理解java内存模型
    线程池的理解
    Thread的理解
    ThreadLocal的理解
    排序算法(简)
    排序算法
    【Java集合源码剖析】LinkedHashmap源码剖析
    vsftp上传文件权限问题
    xp 通过注册表修改环境变量
  • 原文地址:https://www.cnblogs.com/kk942260238/p/14294865.html
Copyright © 2011-2022 走看看