Pythonsocket上传和下载文件

Pythonsocket上传和下载文件


服务端:

import socket ,os,json


server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

server.bind(('',9999))

server.listen(5)

while True:
    conn,addr = server.accept()
    print('conn is addr :',addr)
    while True:
        cmd_obj = conn.recv(1024).decode()
        print('cmd_obj=%s'%cmd_obj)
        if not cmd_obj:break
        if cmd_obj == 'get':
            filename = r'D:\\IStudy\\Oracle\\1.jpg'
            basefilename = os.path.basename(filename)
            myfile = open(filename,'rb')
            myfile_size = os.path.getsize(filename)
            print(basefilename)
            data = {'filename':basefilename,'filesize':myfile_size}
            json_obj = json.dumps(data)
            conn.send(json_obj.encode())
            for readline in myfile:
                conn.send(readline)
            else:
                conn.send(b'finish')
                print('file send is finish')

客户端:

import socket,json

client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(('127.0.0.1',9999))

while True:
    data = input('>>')
    client.send(data.encode())
    json_obj = client.recv(1024).decode()
    file_info = json.loads(json_obj)
    filename = file_info['filename']
    filesize = file_info['filesize']
    print('filename=',filename,'filesize=',filesize)
    recevie_size = 0
    myfile = open(filename,'wb')
    while recevie_size < filesize:
        
        filedata = client.recv(1024)
        myfile.write(filedata)
        recevie_size += len(filedata)
    else:
        myfile.close()
        print('receive file finished!')


测试过图片,文本都可以。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值