博客
关于我
【Python】网络编程--解决粘包问题--简单版:
阅读量:366 次
发布时间:2019-03-04

本文共 1816 字,大约阅读时间需要 6 分钟。

网络编程解决粘包问题——简单版

1. 服务端启动

服务端启动时,首先需要绑定指定的IP地址和端口号。这里使用的端口号是9909。服务端需要监听客户端的连接请求,并准备接收客户端发送的命令。

import socketimport subprocessimport structphone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)phone.bind(('127.0.0.1', 9909))phone.listen(5)print('starting...')

2. 接收客户端连接

服务端进入监听模式后,会等待客户端的连接请求。一旦有客户端连接,服务端就会接收并处理客户端发送的命令。

while True:    conn, client_addr = phone.accept()    print(f'连接来自:{client_addr}')    while True:        try:            # 接收命令            cmd = conn.recv(8096)            if not cmd:                break            # 执行命令并获取结果            obj = subprocess.Popen(                cmd.decode('utf-8'),                shell=True,                stdout=subprocess.PIPE,                stderr=subprocess.PIPE            )            stdout = obj.stdout.read()            stderr = obj.stderr.read()            # preparing header            total_size = len(stdout) + len(stderr)            header = struct.pack('i', total_size)            # 发送结果            conn.send(header)            conn.send(stdout)            conn.send(stderr)        except ConnectionResetError:            break        conn.close()

3. 客户端发送命令

客户端通过socket连接到服务端,发送命令并接收结果。客户端需要处理报头和真实数据。

import socketimport structphone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)phone.connect(('127.0.0.1', 9909))while True:    cmd = input('> ').strip()    if not cmd:        continue    phone.send(cmd.encode('utf-8'))    # 接收结果    header = phone.recv(4)    total_size = struct.unpack('i', header)[0]    recv_size = 0    recv_data = b''    while recv_size < total_size:        recv_data += phone.recv( total_size - recv_size )        recv_size += len(recv_data)

4. 数据传输流程

  • 客户端发送命令:通过socket发送命令字符串。
  • 服务端接收命令:服务端接收命令并执行。
  • 服务端准备结果:将执行结果的标准输出和标准错误分别读取,并打包成固定长度的报头。
  • 发送结果:服务端先发送报头,再发送标准输出和标准错误。
  • 这种方式可以确保客户端能够准确接收服务端返回的完整数据,避免因传输过程中的丢包导致的数据错误。

    转载地址:http://fpyg.baihongyu.com/

    你可能感兴趣的文章
    Vue.js 学习总结(16)—— 为什么 :deep、/deep/、>>> 样式能穿透到子组件
    查看>>
    nopcommerce商城系统--文档整理
    查看>>
    NOPI读取Excel
    查看>>
    NoSQL&MongoDB
    查看>>
    NoSQL介绍
    查看>>
    NoSQL数据库概述
    查看>>
    Notadd —— 基于 nest.js 的微服务开发框架
    查看>>
    NOTE:rfc5766-turn-server
    查看>>
    Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
    查看>>
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>