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

    socket文件上传下载

    # server
    
    import socket
    import json
    import struct
    import os
    
    sk = socket.socket()
    sk.bind(('127.0.0.1',8080))
    sk.listed(5)
    
    while True:
        conn,addr = sk.accept()
        while True:
            dic = {'size':os.path.getsize('test.py'),'name':'shabi.py'}
            dic_b = bytes(json.dumps(dic),encoding= 'utf8')
            dic_b_len = len(dic_b)
            obj = struct.pack('i',dic_b_len)
            conn.send(obj)  # 发送打包好的
            conn.send(dic_b)
            with open('test.py','rb') as f:
                for i in f:
                    conn.send(i)
        conn.close()
    sk.close()
    
    # client
    
    import socket
    import struct
    import json
    
    sk.socket.socket()
    sk.connect(('127.0.0.1',8080))
    sure = input('开始接收>>>?')
    if sure == 'y':
        head_len = struct.unpack("i",sk.recv(4))[0]
        dic = json.loads(sk.recv(head_len))
        l = dic['size']
        name = dic['name']
        c = 0
        data = b''
        with open(name,'wb') as f:
            while c<l:
                if l<1024:
                    data_in = sk.recv(l)
                else:
                    if l-c>1024:
                        data_in = sk.recv(1024)
                    else:
                        data_in = sk.recv(l-c)
                data += data_in
                c += len(data_in)
            f.write(data)
        print(f'{name}文件接收完成!')
    else:
        print('接收失败!')
    sk.close()
    
  • 相关阅读:
    HashMap 和HashTable
    两种方式获得键盘录入
    打印流 printStream
    对象操作流--存储对象
    内存输出流
    序列流
    装饰设计模式
    递归
    IO流(使用指定的码表读写字符)
    IO-字符流 练习
  • 原文地址:https://www.cnblogs.com/dadazunzhe/p/11495422.html
Copyright © 2011-2022 走看看