遇到 [Errno 104] ECONNRESET 错误通常表明客户端(在这种情况下是浏览器)意外关闭了连接,或者连接在数据传输过程中被中断。这可能是由多种因素造成的,包括网络延迟、客户端超时设置、服务器响应延迟等。下面我们将进行一些调整来尝试解决这个问题。
我们可以通过增加异常处理来捕捉这类错误,避免因为单个请求错误导致整个服务器崩溃,并尝试调整图像传输的处理方式,确保即使在网络环境不稳定的情况下也能尽可能稳定运行。
优化代码
python
複製程式碼
import network
import socket
import camera
import time
import gc
# Wi-Fi 设置
SSID = "Bili-Net"
PASSWORD = "0932388283"
def init_camera():
try:
camera.init()
camera.framesize(camera.FRAME_XGA) # XGA (1024x768)
camera.pixformat(camera.PIXFORMAT_JPEG) # JPEG 格式
camera.quality(12) # 图像质量,1-63,数值越小质量越高
print("摄像头初始化成功,分辨率设置为 XGA (1024x768)")
except Exception as e:
print("摄像头初始化失败:", e)
def connect_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
time.sleep(1)
print('连接成功,IP 地址为:', wlan.ifconfig()[0])
def web_page():
return """<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ESP32-CAM 实时图像</title>
<style>
body {text-align: center; font-family: Arial;}
img {width: auto; max-width: 100%;}
</style>
<script>
function refreshImage() {
var img = document.getElementById("camera");
img.src = "/image.jpg?t=" + new Date().getTime();
}
setInterval(refreshImage, 200); // 每 200 毫秒刷新一次图像
</script>
</head>
<body>
<h1>ESP32-CAM 实时图像</h1>
<img id="camera" src="/image.jpg" alt="Camera Image">
</body>
</html>
"""
def handle_client(conn):
try:
request = conn.recv(1024).decode('utf-8')
print('客户端请求:', request)
if 'GET /image.jpg' in request:
img = camera.capture()
if img:
conn.send(b'HTTP/1.1 200 OK\r\n')
conn.send(b'Content-Type: image/jpeg\r\n')
conn.send(b'Connection: close\r\n\r\n')
conn.sendall(img)
else:
print("图像捕获失败,捕获的图像为空")
conn.send(b'HTTP/1.1 503 Service Unavailable\r\n')
conn.send(b'Content-Type: text/plain\r\n')
conn.send(b'Connection: close\r\n\r\n')
else:
response = web_page()
conn.send(b'HTTP/1.1 200 OK\r\n')
conn.send(b'Content-Type: text/html; charset=utf-8\r\n')
conn.send(b'Connection: close\r\n\r\n')
conn.sendall(response.encode('utf-8'))
except Exception as e:
print('处理客户端请求时发生错误:', e)
finally:
conn.close()
gc.collect()
def start_server():
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(5)
print('服务器正在运行,等待客户端连接...')
return s
def main():
connect_wifi(SSID, PASSWORD)
init_camera()
s = start_server()
while True:
conn, addr = s.accept()
print('连接来自:', addr)
handle_client(conn)
if __name__ == '__main__':
main()
增加了详细的错误捕捉:这有助于在客户端突然关闭连接时,服务器不会崩溃,而是捕捉错误并继续运行。
连接关闭处理:确保每次连接在发送完数据或者遇到错误后都能正确关闭,以避免资源泄露。
请确保您的 ESP32-CAM 正确连接并已通过 Wi-Fi 连接到网络。
将上述代码上传到 ESP32-CAM 设备并运行。
在浏览器中访问设备的 IP 地址,查看实时图像是否可以稳定显示。
如果仍有问题或需要进一步的帮助,欢迎随时与我联系。