侧边栏壁纸
博主头像
suke

ah?

  • 累计撰写 54 篇文章
  • 累计创建 38 个标签
  • 累计收到 103 条评论

目 录CONTENT

文章目录

python+socket+文件传输

suke
2020-07-29 / 2 评论 / 0 点赞 / 1,633 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2020-07-29,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

客户端:

import socket
import json
import os
import struct


#实例化
sk = socket.socket()
#定义连接的ip和port
ip_port = ('127.0.0.1',8888)
#服务器连接
sk.connect(ip_port)

filePath = 'D:/360极速浏览器下载/A11_0.wav'
fileSize = os.path.getsize(filePath)
 # 按照规则进行打包
sk.send('{}|{}'.format( 'A11_0.wav',fileSize).encode())
while True:
	res01 = sk.recv(1024)
	if res01.decode() == 'ok':
		sendSize = 0
		# #打开文件
		with open(filePath,'rb') as f:
		    #按每一段分割文件上传
		    for i in f:
		        sk.send(i)
		        sendSize += len(i)
		        #等待接收完成标志
		        data=sk.recv(1024)
		        res = json.dumps(data.decode())
		        print(res)
		        print(fileSize)
		        print(sendSize == fileSize )
		        if sendSize == fileSize:
		        	break

服务端:

import socket
import threading
import sys
import json
import struct


ip_port=('127.0.0.1',8888)
msg = '链接服务端成功'
def server_start():
    sk = socket.socket()
    try:
        #绑定监听
        sk.bind(ip_port)
        #最大连接数
        sk.listen(5)
    except Exception as e:
        print(e)
        sys.exit(1)

    print('启动成功,等待链接',ip_port)

    while True:
        conn,addr = sk.accept()
        conn.send(msg.encode())
        t = threading.Thread(target=dispose_data,args=(conn,addr))
        t.start()


def dispose_data(conn,addr):
    while True:
        try:
            data = conn.recv(1024)
            filename, filesize = data.decode().split('|')
            # filename = filename.decode().strip(b"\x00".decode())
            print(filename,filesize)
            file_size_total = int(filesize)
            received_size = 0
            conn.send('ok'.encode())
            while True:
                with open('./'+filename,'ab') as f:
                    filedata = conn.recv(1024)
                    f.write(filedata)
                    received_size += len(filedata)  # 计算剩余数据包大小
                    print(file_size_total,received_size)
                    if received_size < file_size_total:
                        conn.send(json.dumps({'status':100,'message':'upload ing'}).encode())
                    else:
                       
                        print('接收完毕')
                        break
        except ConnectionResetError as e:
            print('客户端{0}断开'.format(addr),e)
            conn.close()
            sys.exit(1)
        if data == exit:
            print('{0} client connect close'.format(addr))
            break
    conn.close()




# 文件操作
def file_operator(data,conn):
    file_size_total = 1024
    received_size = 0
    print(len(data))
    with open('./'+'aaa.wav','ab') as f:
        f.write(data)
        received_size += len(data)
        if received_size >= file_size_total:
            conn.send(json.dumps({'status':200,'message':'upload success'}).encode())
        else:
            conn.send(json.dumps({'status':100,'message':'uploading...'}).encode())




if __name__ == "__main__":
    server_start()

0

评论区