You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建含while循环线程后Python Socket服务脚本执行停滞问题咨询

问题分析

你的代码中主线程的print("A")没有输出,核心原因是标准输出缓冲区未及时刷新:

  • server.run()线程启动后,会执行到self.server.accept()(阻塞等待客户端连接),但这不会阻塞主线程,主线程本应继续执行自身的while True循环。
  • 看不到"A"是因为默认情况下print会将内容存入缓冲区,未立即显示到控制台。
修复步骤

1. 强制刷新输出缓冲区

修改主线程的print语句,添加flush=True参数强制立即输出:

from server import Server
import threading

server = Server('192.168.178.30', 8001)
thread = threading.Thread(target=server.run)
thread.start()

while True:
    try:
        print("A", flush=True)
    except KeyboardInterrupt:
        break

2. 补充键盘输入逻辑(实现核心需求)

你的目标是将PC键盘输入发送到树莓派,需要在主线程读取输入并更新server.message,同时优化stream函数避免无意义的空数据发送:

修改Server类的stream方法:

def stream(self):
    while True:
        if self.message:
            self.client.send(self.message.encode('utf-8'))
            self.message = ""  # 发送后清空,避免重复发送

修改主脚本的循环:

from server import Server
import threading

server = Server('192.168.178.30', 8001)
thread = threading.Thread(target=server.run)
thread.start()

while True:
    try:
        # 读取键盘输入并赋值给server的message属性
        user_input = input("请输入要发送的内容:")
        server.message = user_input
    except KeyboardInterrupt:
        print("\n程序退出")
        break

3. 额外优化点

  • 将stream线程设为守护线程,主线程退出时自动终止这些线程:
    thread = threading.Thread(target=self.stream, daemon=True)
    thread.start()
    
  • 调整run方法的打印逻辑,避免重复输出监听提示:
    def run(self):
        print('Server is running and listening ...')
        while True:
            self.client, address = self.server.accept()
            print(f'Connection is established with {str(address)}')
            thread = threading.Thread(target=self.stream, daemon=True)
            thread.start()
    

内容的提问来源于stack exchange,提问作者Selim Cifci

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 19:17:03