娱乐小项目4-socket文件传输

1,固定行传送文件

'''文件发送-client'''
import socket
import os
import json
import struct

sk = socket.socket()
sk.connect(('10.181.22.132', 6000))

directory = '***'
size = os.path.getsize(directory)
str_dic = json.dumps({'filename': directory, 'filesize': size}).encode('utf-8')
sk.send(struct.pack('i', len(str_dic)))
sk.send(str_dic)

with open(directory, mode='rb') as f:
    for line in f:
        length = len(line)
        print(length)
        sk.send(struct.pack('i', length))
        sk.send(line)

sk.close()
'''文件接收-server'''
import socket
import os
import json
import struct

sk = socket.socket()
sk.bind(('10.181.22.132', 6000))
sk.listen()

conn, _ = sk.accept()
length = struct.unpack('i', conn.recv(4))
dic_info = json.loads(conn.recv(length[0]).decode('utf-8'))
directory = dic_info['filename']
size = dic_info['filesize']

with open(f'{directory}', mode='wb') as f:
    while size > 0:
        length = struct.unpack('i', conn.recv(4))
        print(f'》》{size}')
        print(length)
        msg = conn.recv(length[0])
        f.write(msg)
        size -= length[0]

if os.path.getsize(f'recv\\{directory}') == dic_info['filesize']:
    print('\033[32m成功接收文件!\033[0m')
else:
    print('\033[31m接收文件失败!\033[0m')

2,固定字节传送文件-更稳定

'''文件发送-client'''
import socket
import os
import json
import struct

sk = socket.socket()
sk.connect(('10.181.22.132', 6000))

directory = '***'
size = os.path.getsize(directory)
str_dic = json.dumps({'filename': directory, 'filesize': size}).encode('utf-8')
sk.send(struct.pack('i', len(str_dic)))
sk.send(str_dic)

with open(directory, mode='rb') as f:
    while size > 0:
        sk.send(f.read(1024*1024*10))
        size -= 1024*1024*10

sk.close()
'''文件接收-server'''
import socket
import os
import json
import struct
import time

sk = socket.socket()
sk.bind(('10.181.22.132', 6000))
sk.listen()

conn, _ = sk.accept()
length = struct.unpack('i', conn.recv(4))
dic_info = json.loads(conn.recv(length[0]).decode('utf-8'))
directory = dic_info['filename']
size = dic_info['filesize']

startTime = time.time()
with open(f'{directory}', mode='wb') as f:
    while size > 0:
        f.write(conn.recv(1024*1024*10))
        size -= 1024*1024*10
        print(size)
# print(f'传输速度为{size/8/1024/(time.time()-startTime)}MB/s')

if os.path.getsize(f'{directory}') == dic_info['filesize']:
    print('\033[32m成功接收文件!\033[0m')
else:
    print('\033[31m接收文件失败!\033[0m')

3,遗留问题

  • 大文件传送失败,总是有文件损毁。
  • 接收端部署到远程服务器,那么发送端(绑定公网ip)和接收端(绑定127.0.0.1)的ip应该怎么写?连接远程接收端时目标计算机积极拒绝,无法连接,是安全组的问题?
posted @ 2021-07-22 10:47  tensor_zhang  阅读(76)  评论(0编辑  收藏  举报