作业:

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()

Day29作业及默写的更多相关文章

  1. Day20作业及默写

    1.请使用C3算法计算出链接图中的继承顺序-Link 一 graph BT id1[A]-->id2[B] id2[B]-->id6[F] id6[F]-->id7[G] id1[A ...

  2. Day11作业及默写

    1.写函数,传入n个数,返回字典{'max':最大值,'min':最小值} 例如:min_max(2,5,7,8,4) 返回:{'max':8,'min':2}(此题用到max(),min()内置函数 ...

  3. Day10作业及默写

    1,继续整理函数相关知识点,写博客. 2,写函数,接收n个数字,求这些参数数字的和.(动态传参) def func(*number): sum=0 for num in number: sum+=nu ...

  4. Day14作业及默写

    1.整理今天所学内容,整理知识点,整理博客. pass 2.画好流程图. pass 3.都完成的做一下作业(下面题都是用内置函数或者和匿名函数结合做出): pass 4.用map来处理字符串列表,把列 ...

  5. Day13作业及默写

    1. 整理今天的博客,写课上代码,整理流程图. 博客链接--博客园 2. 写一个函数完成三次登陆功能: 用户的用户名密码从一个文件register中取出. register文件包含多个用户名,密码,用 ...

  6. Day9作业及默写

    1,整理函数相关知识点,写博客. 2,写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者. def func(obj): return obj[1::2] 3, ...

  7. Day8作业及默写

    1,有如下文件,a1.txt,里面的内容为: 老男孩是最好的培训机构, 全心全意为学生服务, 只为学生未来,不为牟利. 我说的都是真的.哈哈 分别完成以下的功能: 将原文件全部读出来并打印. with ...

  8. Day7作业及默写

    1. 判断一个数是否是水仙花数, 水仙花数是一个三位数, 三位数的每一位的三次方的和还等于这个数. 那这个数就是一个水仙花数. 例如: 153 = 1**3 + 5**3 + 3**3 InputNu ...

  9. Day6作业及默写

    1.使⽤循环打印以下效果: 1: * ** *** **** ***** for num in range(1,6): print('*' * num) 2: ***** **** *** ** * ...

随机推荐

  1. python模块安装报错大全

    报错 环境 解决 手动安装pip install mysqlclient 报错: _mysql.c(29) : fatal error C1083: Cannot open include file: ...

  2. 【IDEA】【5】快捷键

    前言: 1,更改快捷键:File->Settings->Keymap 2,我自定义的快捷键 shitf+alt+s getter,setter,toString方法 (修改处:Keymap ...

  3. vue中使用transition标签底部导航闪烁问题

    <transition :name="transitionName" :duration="{ enter: 500, leave: 0 }" > ...

  4. oracle数据库中字符乱码

    1.1         88.152 os已安装中文包,以下确认os层面中文是否可以显示 1.2         88.153 os没有安装中文包,以下确认os层面中文无法显示 1.3         ...

  5. vue+vue-resource+vue-cookie随笔

    vue-resource http拦截器interceptors: Vue.http.interceptors.push(function(request, next) {...} V-cookie: ...

  6. win10输入法五笔设置

    win10 settings inputApp 1●安装五笔qq ignore / ign ɔ:   2● 操作步骤   3● 五笔设置  

  7. textext for Inkscape

    http://askubuntu.com/questions/417212/inkscape-with-textext http://www.timteatro.net/2010/08/05/text ...

  8. ubuntu 挂载虚拟机vdi文件

    sudo apt-get  install nbd-server  nbd-client  qemu-kvm # rmmod nbd # modprobe nbd max_part=8 # qemu- ...

  9. How to calculate bits per character of a string? (bpc) to read

      http://stackoverflow.com/questions/17797922/how-to-calculate-bits-per-character-of-a-string-bpc up ...

  10. python 列表切片

    列表切片是python语言独有的特征,大大方便了我们的编码. 首先,在介绍切片之前,必须要知道一个知识,就是python列表的读写,下标可以使用负数. insert,get,set 操作均可传入负数下 ...