• socket 上传文件代码


    server.py

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-

    import socket
    import os,hashlib

    ip_port = ('127.0.0.1',6969)
    sk = socket.socket()
    sk.bind(ip_port)
    sk.listen(5)

    while True:
    conn,address = sk.accept()
    while True:
    print('等待新指令')
    #获取客户端发来的操作指令
    data = conn.recv(1024)
    if not data:
    print('客户端已经断开')
    break
    cmd,filename= data.decode().split()
    if os.path.isfile(filename):
    #读取客户端指定的文件
    f=open(filename,'rb')
    m = hashlib.md5()
    file_size = os.stat(filename).st_size
    print('file_size:',file_size)
    # 将客户端指定的文件大小返回客户端
    conn.send(str(file_size).encode('utf-8'))
    #接收sk.send(b"ready to recv file")
    conn.recv(1024)
    for line in f:
    #读取文件的内容,并修改成密文
    m.update(line)
    # 发送改成密文后的文件内容
    conn.send(line)
    f.close()
    conn.close()


    client.py
    #!/usr/bin/env python
    # coding:utf-8


    import socket
    import sys
    import os

    ip_port = ('127.0.0.1', 6969)
    sk = socket.socket()
    sk.connect(ip_port)

    while True:
    # 客户端输入要下载文件的路径,get开头
    cmd = input('path:').strip()
    if len(cmd) == 0:
    continue
    if cmd.startswith('get'):
    # 发送操作指令
    sk.send(cmd.encode())
    file_size = sk.recv(1024)
    print('file_size:',file_size)
    # 发送准备好的信息
    sk.send(b"ready to recv file")
    file_total_size = int(file_size.decode())
    receive_size = 0
    #file_name =cmd.split()[1]
    file_name = 'hah.log'
    f = open(file_name,'wb')
    while receive_size <file_total_size:
    # 接收发送的密文,并写入新文件中
    data = sk.recv(1024)
    receive_size +=len(data)
    f.write(data)
    else:
    print('file recv done')
    f.close()

    sk.close()


  • 相关阅读:
    liunx挂载Ios镜像文件
    liunx下删除多个目录下的相同文件
    tomcat启动报错:Unable to complete the scan for annotations for web application [] due to a StackOverflow
    lr中controller 中scenario-> rendezvous显示灰色不可用
    liunx 下在指定文件夹下搜索字符
    python运行时提示:dot not in the path
    1.4 python 类型转换函数
    js字符串拼接
    自己写的时间轴空控件
    ios禁止页面下拉
  • 原文地址:https://www.cnblogs.com/yoyo008/p/9648036.html
Copyright © 2020-2023  润新知