上传文件

通过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()

 

转载于:https://www.cnblogs.com/blue-tea/p/11344063.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值