zoukankan      html  css  js  c++  java
  • 上传文件

    通过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()
  • 相关阅读:
    ls命令设计思想
    Collection框架
    Yosemite 的问题
    mac vim的alt键无法正常映射
    Word Ladder
    vim自动补全
    Clone Graph
    C# 关于接口与基类的理解(二者的区别)
    C# 操作Excel基础篇(读取Excel、写入Excel)
    C# 随机数 Radom 循环生成同一的数字
  • 原文地址:https://www.cnblogs.com/blue-tea/p/11344063.html
Copyright © 2011-2022 走看看