循环调用requests.get时出现socket closed错误,该如何解决?
问题描述
在树莓派上循环调用urequest1.get(对应requests.get逻辑)时出现socket closed错误,使用的urequest1.py为第三方实现的轻量HTTP请求模块。
报错日志
waiting for connection...
connected ip = 192.168.50.17
Start reading http
Socket closed
Traceback (most recent call last):
File "", line 36, in
File "", line 22, in getSignSession
File "urequest1.py", line 250, in get
File "urequest1.py", line 131, in request
KeyboardInterrupt
代码片段
import urequest1 import urequests import ujson from machine import Pin import utime import gc import netman def getSignSession(): headers = { 'Host': ' app.workato.com', 'User-Agent': ' Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:105.0) Gecko/20100101 Firefox/105.0', 'Accept': ' application/json, text/plain, */*', 'Accept-Language': ' en-US,en;q=0.5', 'Referer': ' https://app.workato.com/users/sign_in', 'Content-Type': ' application/json', 'Connection': ' keep-alive', 'Sec-Fetch-Dest': ' empty', 'Sec-Fetch-Mode': ' cors', 'Sec-Fetch-Site': ' same-origin' } response = urequest1.get('https://app.workato.com/web_api/auth_user.json', headers=headers) #x_csrf_token = response.cookies["XSRF-TOKEN"] while True: try: getSignSession() except OSError as e: continue
解决思路与方案
1. 强制释放连接资源
轻量HTTP库通常不会自动关闭连接,循环调用会导致socket资源耗尽。修改getSignSession函数,每次请求后手动关闭响应对象:
def getSignSession(): # ... 原有代码 ... response = urequest1.get(...) # 若需要处理响应数据,在此处完成 response.close() # 手动关闭连接
同时将headers中的Connection字段改为close,强制服务器在请求结束后关闭连接:
'Connection': ' close',
2. 添加请求间隔
无间隔循环请求会触发服务器限流机制,直接关闭socket。在循环中添加延时:
while True: try: getSignSession() utime.sleep(5) # 间隔5秒,根据实际场景调整 except OSError as e: utime.sleep(2) # 出错后稍作等待再重试 continue
3. 替换HTTP库测试
若urequest1存在socket处理缺陷,可替换为官方urequests模块验证:
# 替换urequest1.get为urequests.get response = urequests.get('https://app.workato.com/web_api/auth_user.json', headers=headers) response.close()
4. 优化内存管理
树莓派(尤其是MicroPython环境)内存有限,循环调用易引发内存泄漏。每次请求后手动触发垃圾回收:
def getSignSession(): # ... 原有代码 ... response.close() gc.collect() # 主动回收内存
内容的提问来源于stack exchange,提问作者user18566545
相关产品推荐
相关产品推荐

