关于python中socket接收数据验证完整并且拼接方法

1. 在传送数据的时候将信息的长度保存在一个由8位字节保存的数据中, 每次根据长度去取对应的数据,

server端

#! /usr/bin/env python
# coding=utf-8
from socketserver import BaseRequestHandler, ThreadingTCPServer


class Handler(BaseRequestHandler):

    def setup(self) -> None:
        self.request.settimeout(1)

    def handle(self):
        while 1:
            try:
                data = "这是主机端的信息"
                length = len(data.encode())
                length_string = "0" * (8 - len(str(length))) + str(length)
                print(length_string)
                self.request.sendall(length_string.encode() + data.encode())
            except BaseException as e:
                print(e)
                print("关闭连接:{}".format(self.client_address[0]))
                break


if __name__ == '__main__':
    host = ("localhost", 8000)
    server = ThreadingTCPServer(host, Handler)
    server.serve_forever()

client端

#! /usr/bin/env python
# coding=utf-8
import socket
import time


client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = ("localhost", 8000)

client.connect(host)

remainging = b""

while 1:
    data = client.recv(2001)
    if len(data) <= 0:
        break
    data = remainging + data

    coursor = 0
    while coursor < len(data):
        size = int(data[coursor:8+coursor].decode())
        infos = data[8+coursor:8+coursor+size].decode()
        coursor = 8 + coursor + size
        print(infos)
        print(coursor, 111)
        if len(data) - coursor <= 8:
            break
        else:
            if coursor + int(data[coursor:coursor+8].decode()) + 8 > len(data):
                break

    remainging = data[coursor:]


    time.sleep(1)

你可能感兴趣的:(关于python中socket接收数据验证完整并且拼接方法)