Day29作业及默写

时间:2022-01-01 23:47:35

作业:

1\ 默写 黏包协议

2\ 上传大文件(文件\视频\图片)

3\ 和你的同桌调通 从你的计算机上传一个视频到你同桌的电脑上

4\ 进阶 : 带上登录

Server

#Server
#!/usr/bin/env python
# encoding: utf-8
# Author: meimeilong <2559184081@qq.com>
# Create Date: 2019-04-10 13:29:26
# Last Modified: 2019-04-10 13:29:26
# Description:
import os
import json
import struct
import socket

sk = socket.socket()
server_addr = ('0.0.0.0',9000)
sk.bind(server_addr)
sk.listen()
def bytes2human(n):
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.1f%s' % (value,s)
    return '%sB' % n
def FormatDic(head_dic):
    for key in head_dic:
        if key == 'filesize':
            print(key,bytes2human(head_dic[key]))
        else:
            print(key,head_dic[key])
    print('传输完成'.center(20,'='))
def GetFile(file_head,buffer=1024,dir='upload'):
    upfile = os.path.join(dir,file_head['filename'])
    filepath='pp.mp4'
    filesize = file_head['filesize']
    with open(upfile,'wb') as f:
        while filesize:
            if filesize >= buffer: #>=是因为如果刚好等于的情况出现也是可以的。
                content = conn.recv(buffer)
                f.write(content)
                filesize -= buffer
            else:
                content = conn.recv(buffer)
                f.write(content)
                return True

while True:
    conn,addr = sk.accept()
    dic_len = struct.unpack('i',conn.recv(4))[0]
    file_dic = conn.recv(dic_len).decode('utf-8')
    head_dic = json.loads(file_dic)
    FormatDic(head_dic)
    GetFile(head_dic)

    conn.close()
sk.close()
##Client
#!/usr/bin/env python
# encoding: utf-8
# Author: meimeilong <2559184081@qq.com>
# Create Date: 2019-04-10 13:31:44
# Last Modified: 2019-04-10 13:31:44
# Description:
import os
import sys
import time
import json
import struct
import socket

def GetHead(filepath):
    abspath = os.path.abspath(filepath)
    filename = os.path.basename(abspath)
    filedir = os.path.dirname(abspath)
    filesize = os.path.getsize(abspath)
    tcp_head = {
        'filename':filename,
        'filedir':filedir,
        'filesize':filesize,
    }
    return tcp_head

def SendHead(tcp_dic):
    str_dic = json.dumps(tcp_dic)
    bytes_dic = str_dic.encode('utf-8')
    num = struct.pack('i',len(bytes_dic))
    sk.send(num)
    sk.send(bytes_dic)
    return True

def progress(percent,width=50):
    '''进度打印功能'''
    if percent >= 100:
        percent=100
    show_str=('[%%-%ds]' %width) %(int(width * percent/100)*"#") #字符串拼接的嵌套使用
    print('\r%s %d%%' %(show_str,percent),end='')

def SendFile(file_head,buffer=1024,recv_size=0):
    filepath = os.path.join(file_head['filedir'],file_head['filename'])
    data_size = file_head['filesize']

    with open(filepath,'rb') as f:
        while data_size:
            if data_size >= buffer: #>=是因为如果刚好等于的情况出现也是可以的。
                content = f.read(buffer)
                sk.send(content)
                data_size -= buffer
                recv_size +=buffer
            else:
                content = f.read(buffer)
                sk.send(content)
                recv_size +=buffer
                return True
            recv_per=int(100*recv_size/data_size) #接收的比例
            progress(recv_per,width=30) #调用进度条函数,进度条的宽度默认设置为30

if __name__ == '__main__':
    sk = socket.socket()
    server_addr = ('127.0.0.1',9000)
    sk.connect(server_addr)

    filepath = input('>>>').strip()
    file_head = GetHead(filepath)
    SendHead(file_head)
    SendFile(file_head)
    sk.close()