基于tcp协议的文件上传

# client
客户端
# 基于tcp传输控制协议 Transmission Control protocol # 上传文件 # 1.通过socket实例化客户端对象client # 2.client连接connect 服务端ip+port 唯一地址与应用程序端口 # ipv4(0.0.0.0)-(255.255.255.255) # port(0-65535)8000之前默认 # flask框架:5000 # django框架:8000 # Mysql数据库:3306 # Redis数据库:6379 # arp协议:通过ip地址解析mac地址 # mac地址(前6:厂 后6:流水线) # # 上传文件先传报头 # 制作报头: # 将字典名file_dict通过json模块dumps转换json格式的字符串 # 而后点语法encode('utf-8')进行编码得到字节bytes格式 # 报头通过struct的 pack 'i'模式(固定4字节),通过内置函数len()得到编码后的字典长度 # # 通过实例化的client对象发送报头 # 通过实例化的client对象发送字典字节格式 import struct import socket import json import os client = socket.socket() client.connect(('127.0.0.1',8081)) file_size = os.path.getsize(r'C:Users86177Desktopwendang.txt') file_name = 'asb.txt' file_dict = { 'file_name':file_name, 'file_size':file_size, 'msg':'上传成功' } file_dict_bytes = json.dumps(file_dict).encode('utf-8') header = struct.pack('i',len(file_dict_bytes)) client.send(header) client.send(file_dict_bytes) import time time.sleep(10) with open(r'C:Users86177Desktopwendang.txt','rb') as f: for line in f: client.send(line)
# server
服务端

import struct import socket import json import os server = socket.socket() server.bind(('127.0.0.1',8081)) server.listen(3) while True: conn,addr = server.accept() while True: try: header = conn.recv(4) if len(header) == 0:continue header_len = struct.unpack('i',header)[0] hender_bytes = conn.recv(header_len) hender_dict = json.loads(hender_bytes.decode('utf-8')) file_size = hender_dict.get('file_size') file_name = hender_dict.get('file_name') recv_size = 0 local = os.path.dirname(__file__) new_file = os.path.join(local,file_name) if not os.path.exists(new_file): with open(new_file,'wb')as f: while recv_size < file_size: dota = conn.recv(1024) f.write(dota) recv_size += len(dota) print(hender_dict.get('msg')) except ConnectionResetError as msg: print(msg) break conn.close()
原文地址:https://www.cnblogs.com/max404/p/10817136.html