cocos creator 3.8.6 websocke的一直报错WebSocket is not a constructor

WebSocket is not a constructor

在cocos creator 3.8.6 构建的安卓应用中,使用了websocket,在运行过程中一直报 WebSocket is not a constructor

解决方法:

. 官方说明

Cocos Creator 3.x(包括 3.8.6)原生平台(Android/iOS)WebSocket 支持,官方文档说明如下:

原生平台:WebSocket 由引擎自动注入,直接用 window.WebSocket 或全局 WebSocket 即可,不需要 WebSocket。

但你遇到 WebSocket is not a constructor,说明全局 WebSocket 没有被注入,可能是构建配置或引擎 bug。

  1. 解决思路

方案一:确认网络模块是否被裁剪

检查构建面板 → 模块设置

确认"网络"模块(network)已勾选。

如果未勾选,原生包不会包含 WebSocket 支持。

重新构建并安装到设备测试

勾选后重新构建、编译、安装。

用法示例

复制代码
   if (sys.isNative && sys.platform === sys.Platform.ANDROID) {
                console.log('Android平台特殊处理', this.host);
                // Android平台特殊处理
                //const cert: string  = 'cert/cert.pem'; // TODO: 处理证书路径
                this.ws = new WebSocket(this.host!, "ws");
                //this.ws = new jsb.WebSocket(this.host!,"ws");
            } else {
                console.log('其他平台特殊处理', this.host);
                this.ws = new WebSocket(this.host!);
            }

方案二:用 cc.Socket(Cocos 3.8.6 新增)

Cocos Creator 3.8.x 开始,原生平台推荐用 cc.Socket,不是 WebSocket。

用法示例

复制代码
import { sys, Socket } from 'cc';

private initSocket(): void {
    if (!this.ws) {
        if (sys.isNative && sys.platform === sys.Platform.ANDROID) {
            console.log('Android平台特殊处理', this.host);
            this.ws = new Socket();
            // 解析 host 和 port
            const url = new URL(this.host!);
            this.ws.connect(url.hostname, Number(url.port));
        } else {
            console.log('其他平台特殊处理', this.host);
            this.ws = new window.WebSocket(this.host!);
        }

        // 事件绑定(cc.Socket 事件和 WebSocket 不完全一样)
        this.ws.on('open', this.connected.bind(this));
        this.ws.on('message', this.message.bind(this));
        this.ws.on('close', this.close.bind(this));
        this.ws.on('error', this.error.bind(this));
        this.notification = new EventTarget();
    } else {
        // ... 你的原有逻辑 ...
    }
}

注意:

cc.Socket 只支持原生平台,Web 端还是用 WebSocket。

事件名和标准 WebSocket 不一样,需用 on('open', ...) 这种方式。

方案三:自定义全局 WebSocket

如果你项目里有 polyfill 或第三方库覆盖了全局 WebSocket,请检查是否有类似代码,避免冲突。

  1. 总结

优先推荐用 cc.Socket,这是 Cocos Creator 3.8.x 官方推荐的原生网络通信方式。

构建时确保"网络"模块已勾选,否则原生包没有网络能力。

Web 端用 window.WebSocket,原生端用 cc.Socket。