You need to enable JavaScript to run this app. Python TCP协议外部交互实现:asyncio Echo客户端建连后修改待发消息方法
优惠活动
大模型
产品
解决方案
定价
更多

Python TCP协议外部交互实现:asyncio Echo客户端建连后修改待发消息方法

可动态调整发送内容的Echo客户端实现

核心改造逻辑

你现有代码的基础已经很接近目标了,只需要补两个关键能力就能实现动态调整:

  • 拿到protocol实例的可写引用,把原来初始化时传入的固定消息,变成可以被外部修改的公开实例属性
  • 搭一条不阻塞事件循环的外部交互通道,在不中断客户端正常收发流程的前提下,接收修改消息的指令

你原来写的write_to_device方法本身就是实时读取self.message的值,只要这个属性能被外部修改,下一次延迟发送触发时就会自动用最新的消息内容,完全不需要改动原有的收发、延迟逻辑。

具体改造步骤

  1. 修正protocol的状态可访问性
    保持EchoClientProtocol里的message为普通公开实例变量,不要加私有封装(比如变成self.__message),确保外部可以直接修改这个值。
  2. 避开阻塞IO的事件循环陷阱
    千万不要直接在asyncio协程里用命令行input()做外部交互,这是最常见的踩坑点:这类阻塞调用会卡住单线程的事件循环,导致服务端回包无法及时打印、1秒延迟的发送任务无法准时执行。正确的做法是用asyncio.to_thread()把阻塞的输入操作丢到独立的后台线程池运行,完全不占用事件循环的调度时间。
  3. 并行跑交互任务和客户端主流程
    原来的main协程一直阻塞等待连接断开的信号,根本没有多余的调度时间处理外部输入。改造后需要把输入处理任务和连接监听任务并行运行,等连接断开时自动取消还在等待输入的任务,避免程序卡死无法退出。

完整可运行的改造代码

import asyncio

class EchoClientProtocol(asyncio.Protocol):
    def __init__(self, message, on_con_lost):
        # 公开可修改的消息属性
        self.message = message
        self.on_con_lost = on_con_lost
        self.loop = asyncio.get_running_loop()

    def connection_made(self, transport):
        self.transport = transport
        transport.write(self.message.encode())
        print('Data sent: {!r}'.format(self.message))

    def write_to_device(self):
        self.transport.write(self.message.encode())
    
    def data_received(self, data):
        print('Data received: {!r}'.format(data.decode()))
        self.loop.call_later(1.0 , self.write_to_device)

    def connection_lost(self, exc):
        print('The server closed the connection')
        self.on_con_lost.set_result(True)

# 非阻塞的外部输入处理逻辑
async def input_handler(protocol):
    while True:
        # 将阻塞的input操作移交后台线程,不卡事件循环
        new_msg = await asyncio.to_thread(input, "请输入新的发送内容(回车确认,空输入不修改):")
        if not new_msg.strip():
            continue
        # 直接修改protocol的实例属性,下一次发送就会生效
        protocol.message = new_msg
        print(f"已更新发送内容为: {new_msg!r}")


async def main(): 
    loop = asyncio.get_running_loop()
    on_con_lost = loop.create_future()
    initial_message = 'Hello World!'

    transport, protocol = await loop.create_connection(
        lambda: EchoClientProtocol(initial_message, on_con_lost),
        '127.0.0.1', 8888)

    # 启动并行的输入处理任务
    input_task = asyncio.create_task(input_handler(protocol))

    try:
        # 并行等待两类事件:连接断开、输入任务完成
        done, pending = await asyncio.wait(
            [on_con_lost, input_task],
            return_when=asyncio.FIRST_COMPLETED
        )
        # 连接优先断开时,取消仍在等待输入的挂起任务
        for task in pending:
            task.cancel()
    finally:
        transport.close()
        input_task.cancel()

if __name__ == "__main__":
    asyncio.run(main())

注意事项

  • 所有对protocol.message的修改都会切回asyncio主线程执行,不存在多线程竞态问题,不需要额外加锁
  • 如果你的外部交互来源不是命令行(比如对接配置中心、串口指令、消息队列通知),只需要把input_handler里的输入读取逻辑替换成对应的新消息获取逻辑即可,整体框架不需要改动
  • 不需要引入额外的回调、消息队列等复杂封装,asyncio的单线程模型本身就适合这类共享状态的动态修改

内容的提问来源于stack exchange,提问作者Victor Modamio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.30 17:24:04