执行完成后出现java.net.SocketException: Connection reset报错求助
解决Selenium WebSocket连接重置警告问题
问题重现
运行Selenium脚本后,所有结果均按预期生成,但最后抛出如下警告:
Apr 04, 2023 7:43:38 PM org.openqa.selenium.remote.http.WebSocket$Listener onError WARNING: Connection reset java.net.SocketException: Connection reset at java.base/sun.nio.ch.SocketChannelImpl.throwConnectionReset(SocketChannelImpl.java:394) at java.base/sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:426) at io.netty.buffer.PooledByteBuf.setBytes(PooledByteBuf.java:259) at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1132) at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:357) at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:151) at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:788) at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724) at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Thread.java:833)
原因分析
这个警告是Selenium与浏览器驱动间的WebSocket连接在脚本执行完毕后被强制重置导致的,常见诱因:
- 脚本结束时未正确关闭浏览器驱动实例,驱动进程残留后被系统强制断开连接
- Selenium版本与浏览器驱动(ChromeDriver/GeckoDriver等)版本不匹配
- 浏览器驱动的WebSocket连接超时设置过短
解决方案
1. 显式关闭浏览器驱动会话
脚本执行完成后,必须调用quit()方法彻底终止驱动进程,而非仅关闭窗口的close()方法。示例代码:
// Java示例 WebDriver driver = new ChromeDriver(); try { // 你的业务执行代码 } finally { // 确保销毁整个驱动会话 driver.quit(); }
2. 匹配Selenium与浏览器驱动版本
严格对应版本号:
- Chrome浏览器需搭配同大版本的ChromeDriver(如Chrome 112对应ChromeDriver 112.x)
- Firefox浏览器需根据Selenium版本匹配对应GeckoDriver版本
3. 调整WebSocket超时参数
通过驱动选项延长WebSocket连接超时时间,避免过早断开:
// Chrome示例 ChromeOptions options = new ChromeOptions(); options.setCapability("webSocketTimeout", 30000); // 设置为30秒超时 WebDriver driver = new ChromeDriver(options);
4. 关闭该类日志警告
若警告不影响功能仅干扰日志,可通过日志框架屏蔽该类的警告输出。以Logback为例,在logback.xml中添加:
<logger name="org.openqa.selenium.remote.http.WebSocket$Listener" level="ERROR"/>
验证方式
修改后重新运行脚本,确认执行完毕后无该警告,且浏览器进程被正常终止。
内容的提问来源于stack exchange,提问作者Siddheshwar Mhetre
相关产品推荐
相关产品推荐

