25 struct custom headers and ftp practice

struct custom headers and ftp file transfer

We transfer all the data from the network, called packets, all of the data package, called packets. Message in more than a message containing information to be transmitted, also includes the ip address, mac address, port number, and so on. . .
All messages have a header, which is the protocol decision. Message contained in information such as how many bytes to accept. We can define their own messages in the network transmission, everywhere there is an agreement, the agreement is a pile of messages and headers.
To upload or download a large file

#server端
import socket,json
import struct
sk = socket.socket()
sk.bind(('127.0.0.1',8080))

buffer = 4096
sk.listen()
conn,addr = sk.accept()
#接收

head_len = conn.recv(4)
head_len = struct.unpack('i',head_len)[0]
json_head = conn.recv(head_len).decode('utf-8')
head = json.loads(json_head)
filesize = head['filesize']
with open(head['filename'],'wb')as f:
    while filesize:
        if filesize >= buffer:
            content = conn.recv(buffer)
            f.write(content)
            filesize-=buffer
        else:
            content = conn.recv(filesize)
            f.write(content)
            break
conn.close()
sk.close()
#client端
import struct
import socket,os,json
sk = socket.socket()
sk.connect(('127.0.0.1',8080))
buffer = 4096
#发送文件
head = {'filepath':r'地址',
        'filename':'名字',
        'filesize':None
        }
file_path = os.path.join(head['filepath'],head['filename'])
filesize = os.path.getsize(file_path)
head['filesize'] = filesize
json_head = json.dumps(head)    #字典转成字符串
bytes_head = json_head.encode('utf-8')  #字符串转为bytes

#计算head长度
head_len = len(bytes_head)  #报头长度
pack_len = struct.pack('i',head_len)

sk.send(pack_len)   #先发送报头的长度
sk.send(bytes_head) #发送报头

with open(file_path,'rb') as f:
    while filesize:
        if filesize > buffer:
            content = f.read(buffer)
            sk.send(content)
            filesize -= buffer
        else:
            content = f.read(filesize)
            sk.send(content)
            break
sk.close()

Guess you like

Origin blog.csdn.net/weixin_43265998/article/details/89761162