Sticky questions about the package TCP protocol prone explanation can refer to: https://www.cnblogs.com/Eva-J/articles/8244551.html#_label6
In this part is most refer to the above blog to learn from, record it.
# Struct Module: -> module can be a type, such as numbers, conversion to a fixed length of bytes Import struct RET = struct.pack ( 'I', 4096) # 'I' representatives int, is about to take a digital conversion a fixed length (4 bytes) bytes type Print (RET) NUM = struct.unpack ( 'I', RET) # tuple outputs a print (num [0])
Using a digital pack can be transformed into a fixed length (4 bytes) bytes type, can receive only the four bytes recv time, then it can be resolved unpack then you need to know the size of the file transfer.
The following shows based on the TCP protocol, using the transfer process video files struct carried out:
server.py
# Implementation of a large file upload or download # ip address port number of the configuration file Import socket Import struct Import json SK = socket.socket () sk.bind (( '127.0.0.1', 8080)) sk.listen () Buffer = 4096 Conn, addr = sk.accept () # receiving 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: the 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.py
# 发送端 import socket import os import json import struct sk = socket.socket() sk.connect(('127.0.0.1',8080)) buffer = 4096 # 发送文件 head = {'filepath':r'/Users/zxx/Downloads', 'filename':r'test.mp4', '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') # String transfer bytes pack_len struct.pack = ( 'I', head_len) head_len = len (bytes_head) # calculates the length of the head # Print (bytes_head) # Print (json_head) # Print (head_len, pack_len) sk.send (pack_len) # first transmitter head length sk.send (bytes_head) # bytes in the transmission-type headers with Open (file_path, 'RB') AS F: the while filesize: IF filesize> = Buffer: Content = reached, f.read (buffer) # each read out the contents of sk.send (content) filesize - = Buffer the else: content = f.read (filesize) sk.send (content) BREAK sk.close ()
After server.py has been executed and client.py file, you can transfer to the local working directory python file in the download directory of test.mp4 file.
The results are as follows: