博客园

2、tcp/udp解决粘包

tcp解决粘包,远程控制

tcp客户端

  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_bytes_len = struct.unpack('i',client.recv(4))[0]

      header_bytes = client.recv(header_bytes_len)
      header_json = header_bytes.decode('utf-8')
      header_dic = json.loads(header_json)

      print(header_dic)
      total_size = header_dic['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'))

tcp服务端

  from socket import *
  from subprocess import Popen,PIPE
  import struct
  import json

  server = socket(AF_INET,SOCK_STREAM)
  server.bind(('127.0.0.1',8080))
  server.listen(5)

  while True:
      conn,client_addr = server.accept()
      while True:
          try:
              cmd = conn.recv(8096)
              if len(cmd) == 0: break
              obj = Popen(cmd.decode('utf-8'),
                          shell = True,
                          stderr= PIPE,
                          stdout= PIPE,
                          )      
              res1 = obj.stdout.read()
              res2 = obj.stderr.read()

              header_dic = {
                  'filename': 'a.txt',
                  'total_size': len(res1)+len(res2),
                  'md5': '天王盖地虎'
              }
  
              header_json = json.dumps(header_dic)
              header_bytes = header_json.encode('utf-8')
              conn.send(struct.pack('i',len(header_bytes)))
              conn.send(header_bytes)

              conn.send(res1)
              conn.send(res2)
          except Exception:
              break
      conn.close()

udp 简单的多并发

服务端

  from socket import *

  server= socket(AF_INET,SOCK_DGRAM)
  server.bind(('127.0.0.1',9999))

  while True:

      data,client_addr = server.recvfrom(1024)
      print(data.decode('gbk'))
      server.sendto(data.upper(),client_addr)

客户端1

  from socket import *

  client = socket(AF_INET,SOCK_DGRAM)

  while True:
      data = input('>>>>>>>:').strip()
      client.sendto(data.encode('utf-8'),('127.0.0.1',9999))
      res,server_addr = client.recvfrom(1024)
      print(res.decode('utf-8'))

客户端2

  from socket import *

  client = socket(AF_INET,SOCK_DGRAM)

  while True:
      data = input('>>>>>>>:').strip()
      client.sendto(data.encode('utf-8'),('127.0.0.1',9999))
      res,server_addr = client.recvfrom(1024)
      print(res.decode('utf-8'))
posted @ 2021-01-18 19:09  小刘学python  阅读(129)  评论(0编辑  收藏  举报