You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS WSS服务器与Android Java WSS客户端连接失败排查及替代方案

WSS连接失败问题排查与解决方案

核心问题排查与修复

1. 服务器绑定地址限制

你的Node.js服务器当前仅绑定localhost(127.0.0.1),局域网内的Android设备无法访问。修改服务器监听地址为0.0.0.0,允许所有网卡接入:

server.listen(3000, '0.0.0.0', () => {
    console.log('WebSocket server is running on wss://0.0.0.0:3000');
});

2. 防火墙/端口拦截

  • 检查服务器系统防火墙,确保3000端口已开放(Linux可执行ufw allow 3000,Windows在防火墙高级设置里添加入站规则)。
  • 临时关闭防火墙测试,确认是否是拦截导致的连接失败。

3. SSL证书兼容性问题

自签证书若使用旧加密算法或不匹配的域名,可能被Android拒绝:

  • 重新生成兼容的证书,指定服务器局域网IP为CN字段:
openssl req -x509 -newkey rsa:4096 -keyout server.key -out server.cert -days 365 -nodes -subj "/CN=192.168.10.179"
  • 确保证书使用SHA-256签名(上述命令默认使用),避免SHA-1等已被淘汰的算法。

4. OkHttp连接超时配置

OkHttp默认连接超时为10秒,刚好匹配你的失败时间,延长超时时间:

import java.util.concurrent.TimeUnit;

// ...

return new OkHttpClient.Builder()
        .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0])
        .hostnameVerifier((hostname, session) -> true)
        .connectTimeout(30, TimeUnit.SECONDS) // 延长连接超时到30秒
        .build();

5. Android网络权限缺失

确保AndroidManifest.xml中添加了网络权限:

<uses-permission android:name="android.permission.INTERNET"/>

替代方案

开发阶段使用明文WS(不推荐生产环境)

若仅为开发测试,可配置Android允许明文HTTP/WS连接:

  1. 在res/xml下创建network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">192.168.10.179</domain>
    </domain-config>
</network-security-config>
  1. 在AndroidManifest.xml的application标签中引用:
<application
    ...
    android:networkSecurityConfig="@xml/network_security_config">
    ...
</application>
  1. 服务器改为普通WS:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });

内网穿透工具

使用ngrok等工具将本地WSS服务暴露到公网,避免局域网配置问题:

ngrok http 3000

然后将Android客户端的连接地址改为ngrok提供的HTTPS地址(如wss://xxxx-xx-xx-xx-xx.ngrok.io)。

使用可信CA证书

生产环境建议使用Let's Encrypt等免费CA签发的证书,避免自签证书的兼容性问题。

内容的提问来源于stack exchange,提问作者Lorenzo Cuttitta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 11:34:54