React Native WebSocket在Release模式下无法连接问题求助
React Native Release模式WebSocket连接失败(状态码3)排查与修复
Debug模式下React Native应用可正常连接C# WebSocket服务器,但打包为Release APK后连接失败,WebSocket状态返回3(连接已关闭),可从以下几个方向排查:
1. 网络权限与安全策略问题
- 添加网络权限:确保
AndroidManifest.xml中明确声明网络权限,Debug模式可能默认包含,但Release模式需手动添加:<uses-permission android:name="android.permission.INTERNET" /> - 允许明文流量(Android 9+):若使用
ws://非加密协议,需配置网络安全策略:
在res/xml/network_security_config.xml中添加:
并在<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>AndroidManifest.xml的application标签中引用:android:networkSecurityConfig="@xml/network_security_config"
2. 服务器地址与连通性验证
- 确认Release模式使用的服务器地址为公网可访问地址,避免使用Debug阶段的本地IP(如
192.168.x.x)。 - 检查服务器端口是否开放,防火墙/安全组是否允许客户端IP的WebSocket连接请求。
3. 补充代码异常监听
当前Socket类未监听onerror和onclose事件,无法获取连接失败的具体原因,建议补充:
export default class Socket { socket: WebSocket; constructor(indirizzo: string) { this.socket = new WebSocket(indirizzo); this.socket.onopen = () => { console.log('连接成功'); }; // 添加错误监听,捕获连接异常 this.socket.onerror = (error) => { console.error('WebSocket错误:', error); }; // 添加关闭监听,获取关闭码和详细原因 this.socket.onclose = (event) => { console.log('连接关闭,状态码:', event.code, '原因:', event.reason); }; } Disconnetti() { this.socket.close(); } Manda(nomeEvento: string, messaggio: any) { try { this.socket.send( JSON.stringify({ nomeEvento: nomeEvento, username: messaggio.username, password: messaggio.password, codice: messaggio.codice, movimento: messaggio.movimento, }), ); } catch (e) { console.log(e); } } Ricevi(nomeEvento: string, callback: (risposta: any) => void): any { this.socket.onmessage = e => { try { let risposta = JSON.parse(e.data); if (risposta.nomeEvento === nomeEvento ) { callback(risposta.messaggio); } } catch (e) { console.log(e); } }; } }
打包Release APK后,通过Logcat查看日志,可定位具体失败原因。
4. 避免代码混淆影响
若启用了ProGuard混淆,需在proguard-rules.pro中添加WebSocket相关类的保留规则:
-keep class com.facebook.react.modules.websocket.** { *; }
5. 服务器端验证
- 检查C#服务器是否限制了客户端IP,是否允许Release应用所在网络的连接请求。
- 若使用
wss://加密协议,确保服务器SSL证书有效,客户端设备信任该证书(自签名证书需手动添加到Android系统信任列表)。
内容的提问来源于stack exchange,提问作者Alessio Catrini
相关产品推荐
相关产品推荐

