上传文件

通过pycharm可以实现两台不同电脑之间的互相通信(目前只能上传一个)

客户端
import
os import json import socket import struct client = socket.socket() #创建一个客户套接字 client.connect(("127.0.0.1",8080)) #绑定IP地址和端口 while True: MOVIE = r'E:\视频截图\默写过的内容' ## 写要发送的文件所在的文件夹 movie_list = os.listdir(MOVIE) # 弄成列表 for i, movie in enumerate(movie_list,1):# 进行枚举 print(i,movie) choice = input(">>>:").strip() # 进行选择 if choice == 'q': break if choice.isdigit(): choice = int(choice)-1 if choice in range(0,len(movie_list)): path = movie_list[choice] file_path = os.path.join(MOVIE,path) # 文件的绝对路径 file_size = os.path.getsize(file_path) # 要上传文件的数据 d = { 'file_name':'iphone8.png', 'file_size': file_size} # 字典 json_d = json.dumps(d).encode('utf-8') # json序列化处理 header = struct.pack('i',len(json_d)) #封装成字典报头 # print(header) client.send(header) #将字典报头发送给服务端 client.send(json_d) # 将处理后的字典也发送给服务端 with open(file_path,'rb')as f: # 采用只读模式打开 for i in f : client.send(i) # 将for循坏取出的值依次发送 else: print('not in range') else: print('must be a number')
服务端
import
os import json import socket import struct server = socket.socket() server.bind(('127.0.0.1',8080)) server.listen(5) while True: conn,addr = server.accept() while True: try: header_len = conn.recv(4) header_len = struct.unpack('i',header_len)[0] header_dic = conn.recv(header_len) json_dic = json.loads(header_dic.decode('utf-8')) size = json_dic.get('file_size') recv_size = 0 with open(json_dic.get('file_name'),'wb')as f: while recv_size < size: data = conn.recv(1024) f.write(data) size += len(data) print('上传成功') except ConnectionResetError as e: print(e) break conn.close()

 

posted @ 2019-08-13 09:52  kuanglinfeng  阅读(122)  评论(0编辑  收藏  举报