BeagleBone与电脑Socket通信异常:回传数据报WinError 10057错误
问题:BeagleBone Black与电脑Socket通信无法回传数据
已实现BeagleBone向电脑发送数据,但电脑向BeagleBone回传时出现以下错误:
Socket created Socket bind complete Socket now listening Connected to 192.168.0.120:49378 main:: Begin program... Residual System Status: startup Please address errors. Continue? (Y/N) y Traceback (most recent call last): File ~\Desktop\miles_lybrairy\milesintegration_V0.0.3\MILES\sockettoem.py:41 in <module> s.send(bytes(input(),'UTF-8')) OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
BeagleBone端代码
import Adafruit_BBIO.ADC as ADC import time import socket import sys import os serverAddr = ('192.168.0.11', 20103) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(serverAddr) fsr = 'P9_40' ADC.setup() while True: reading = ADC.read(fsr)*1000 reading = int(round(reading)) stdout =os.system("python3 ./fw102c_control.py") #client.send(bytes("poop")) client.recv(1024) client.close()
电脑端代码
# -*- coding: utf-8 -*- """ Created on Mon Aug 15 13:56:19 2022 @author: GigaGame """ import socket import sys import os HOST = '' PORT = 20103 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('Socket created') try: s.bind((HOST, PORT)) except socket.error as msg: print('Bind failed. ') sys.exit() print('Socket bind complete') s.listen(10) print('Socket now listening') conn, addr = s.accept() print('Connected to ' + addr[0] + ':' + str(addr[1])) while True: data = conn.recv(1024) line = data.decode('UTF-8') # convert to string (Python 3 only) print( line ) s.send(bytes(input(),'UTF-8')) #s.recv()
问题原因及解决办法
核心问题
电脑端代码中,你使用了监听socket s来发送数据,但TCP协议中,监听socket仅用于接受客户端连接,真正和BeagleBone通信的是accept()返回的连接socket conn。直接调用s.send()会触发WinError 10057,因为监听socket本身未与任何客户端建立连接。
修改步骤
修正电脑端发送逻辑:
将电脑端循环内的s.send(bytes(input(),'UTF-8'))改为conn.send(bytes(input(),'UTF-8')),改用连接socket发送数据。完善BeagleBone端数据发送逻辑:
当前BB端仅等待接收数据,未主动发送内容,会导致电脑端conn.recv(1024)长期阻塞,无法进入发送环节。可取消注释client.send(bytes("poop")),或发送采集到的FSR数据,例如:client.send(str(reading).encode('UTF-8'))
修改后的电脑端关键代码片段
while True: data = conn.recv(1024) if not data: # 处理客户端断开连接的情况 break line = data.decode('UTF-8') print( line ) # 使用连接socket发送回传数据 conn.send(bytes(input(),'UTF-8'))
修改后的BeagleBone端关键代码片段
while True: reading = ADC.read(fsr)*1000 reading = int(round(reading)) stdout = os.system("python3 ./fw102c_control.py") # 主动发送采集数据到电脑 client.send(str(reading).encode('UTF-8')) # 接收电脑回传内容 response = client.recv(1024) print("Received from PC:", response.decode('UTF-8'))
内容的提问来源于stack exchange,提问作者Munix0
相关产品推荐
相关产品推荐

