zoukankan      html  css  js  c++  java
  • python 【socket】

    1. 解决黏包的问题
    struct 模块
    https://blog.csdn.net/weixin_33812391/article/details/111905211
    
    # server
    
    import json
    import struct
    import socket
    
    sk = socket.socket()
    sk.bind(('127.0.0.1',8080))
    sk.listen()
    
    conn,addr = sk.accept()
    dic_len = conn.recv(4)  # 4个字节 数字的大小
    dic_len = struct.unpack('i',dic_len)[0]
    content = conn.recv(dic_len).decode('utf-8')  # 70
    content_dic = json.loads(content)
    if content_dic['operate'] == 'upload':
        with open(content_dic['filename'],'wb') as f:
            while content_dic['filesize']:
                file = conn.recv(1024)
                f.write(file)
                content_dic['filesize'] -= len(file)
    conn.close()
    sk.close()
    
    
    
    # client
    import os
    import json
    import struct
    import socket
    
    sk = socket.socket()
    sk.connect(('127.0.0.1',8080))
    
    def get_filename(file_path):
        filename = os.path.basename(file_path)
        return filename
    
    #选择 操作
    operate = ['upload','download']
    for num,opt in enumerate(operate,1):
        print(num,opt)
    num = int(input('请输入您要做的操作序号 : '))
    if num == 1:
        '''上传操作'''
        file_path = input('请输入要上传的文件路径 : ')
        file_size = os.path.getsize(file_path)  # 获取文件大小
        file_name = get_filename(file_path)
        dic = {'operate': 'upload', 'filename': file_name,'filesize':file_size}
        str_dic = json.dumps(dic).encode('utf-8')
        ret = struct.pack('i', len(str_dic))  # 将字典的大小转换成一个定长(4)的bytes
        sk.send(ret + str_dic)
        with open(file_path,'rb') as  f:
            while file_size:
                content = f.read(1024)
                sk.send(content)
                file_size -= len(content)
    elif num == 2:
        '''下载操作'''
    sk.close()
    
    
  • 相关阅读:
    C#中remoting和webservice的区别
    Nhibernate了解(转载)
    深入浅出JSON
    Asp.net页面传值总结(转载)
    .Net ViewState的实现(转载)
    asp.net数据绑定之Eval和Bind区别
    PetShop数据库解读
    .Net 2.0 缓存使用(转载)
    ASP.NET中EVAL用法大全
    a:hover和a:visited书写顺序的重要性
  • 原文地址:https://www.cnblogs.com/amize/p/15196058.html
Copyright © 2011-2022 走看看