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

树莓派基于Python3 Socket双向通信问题:服务器无法接收客户端指令

解决树莓派服务器接收客户端指令的问题

问题描述

已实现树莓派1(服务器端)向树莓派2(客户端)发送消息,但服务器端无法接收客户端返回的指令,需修复该双向通信功能。

现有代码核心问题

  1. 角色逻辑混乱:当前SERVER.py实际是主动发起连接的客户端,CLIENT.py是监听端口的服务器,命名与实际功能不符,导致通信逻辑错位。
  2. 无接收返回逻辑:原服务器端仅实现发送功能,未添加监听接收客户端返回数据的代码;客户端仅接收消息,无返回指令的逻辑。
  3. 端口不匹配:原服务器连接端口(5003)与客户端绑定端口(5002)不一致,会导致连接失败。

修改后的双向通信代码实现

修正后的服务器端(树莓派1)代码

服务器端负责监听端口、接收客户端连接,同时支持发送指令和接收返回:

import socket
import time

print("This is Raspberry Pi 1 as server.")

# 服务器配置
SERVER_IP = '0.0.0.0'  # 监听所有可用网卡
SERVER_PORT = 5003

# 创建套接字并初始化
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_IP, SERVER_PORT))
server_socket.listen(1)

print(f"Server listening on {SERVER_IP}:{SERVER_PORT}")

# 等待客户端连接
client_socket, client_addr = server_socket.accept()
print(f"Connected to client: {client_addr}")

def send_command():
    command = input("Enter command to send to client (or 'exit' to quit): ")
    if command.lower() == 'exit':
        client_socket.close()
        server_socket.close()
        exit()
    try:
        client_socket.sendall(command.encode('utf-8'))
        print(f"Sent command: {command}")
    except Exception as e:
        print(f"Failed to send command: {e}")

def receive_response():
    try:
        response = client_socket.recv(1024)
        if response:
            response_str = response.decode('utf-8')
            print(f"Received response from client: {response_str}")
        else:
            print("Client disconnected.")
            client_socket.close()
            server_socket.close()
            exit()
    except Exception as e:
        print(f"Failed to receive response: {e}")

# 主循环:发送指令并接收客户端返回
while True:
    send_command()
    time.sleep(0.5)  # 等待客户端处理指令
    receive_response()
    time.sleep(1)

修正后的客户端(树莓派2)代码

客户端负责连接服务器、接收指令,并返回响应:

import socket
import time

print("This is Raspberry Pi 2 as client.")

# 服务器配置(替换为树莓派1的实际IP)
SERVER_IP = '192.168.39.46'
SERVER_PORT = 5003

# 创建套接字并连接服务器
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
    client_socket.connect((SERVER_IP, SERVER_PORT))
    print(f"Connected to server {SERVER_IP}:{SERVER_PORT}")
except Exception as e:
    print(f"Failed to connect to server: {e}")
    exit()

def receive_command():
    try:
        command = client_socket.recv(1024)
        if command:
            command_str = command.decode('utf-8')
            print(f"Received command from server: {command_str}")
            return command_str
        else:
            print("Server disconnected.")
            client_socket.close()
            exit()
    except Exception as e:
        print(f"Failed to receive command: {e}")

def send_response():
    # 可根据服务器指令生成业务响应,示例为手动输入返回内容
    response = input("Enter response to send to server: ")
    try:
        client_socket.sendall(response.encode('utf-8'))
        print(f"Sent response: {response}")
    except Exception as e:
        print(f"Failed to send response: {e}")

# 主循环:接收指令并返回响应
while True:
    cmd = receive_command()
    # 可选:添加业务逻辑处理,比如控制硬件设备
    send_response()
    time.sleep(1)

关键修改说明

  • 角色明确:服务器端监听端口等待连接,客户端主动发起连接,符合TCP标准通信逻辑。
  • 双向通信:两端均实现发送与接收函数,支持消息往返。
  • 端口统一:服务器与客户端使用相同端口(5003),确保连接正常。
  • 错误处理:增加异常捕获,处理连接、发送、接收过程中的异常情况。
  • 交互测试:通过输入获取发送内容,方便快速验证功能。

内容的提问来源于stack exchange,提问作者Ace Pash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:40:34