[ERROR]: JS: TypeError: WebSocket is not a constructor

  • Creator 版本:3.7.3

  • 目标平台:android

  • 重现方式:运行报错

  • 首个报错: 2023-07-12 14:35:58.501 22855-22882/? D/Cocos: 14:35:58 [DEBUG]: JS: Success to load scene: db://assets/scene.scene
    2023-07-12 14:35:58.510 22855-22882/? D/Cocos: 14:35:58 [DEBUG]: JS: 01
    2023-07-12 14:35:58.523 22855-22882/? E/Cocos: 14:35:58 [ERROR]: JS: TypeError: WebSocket is not a constructor
    TypeError: WebSocket is not a constructor
    at g.start (assets/main/index.js:5:698)

  • 之前哪个版本是正常的:谷歌浏览器调试正常,上真机就报错,做一个纯websocket调用测试demo也报错

  • 手机型号: 雷电模拟器9

  • 手机浏览器:

  • 编辑器操作系统:

  • 重现概率: 100%

测试代码:

private socket:WebSocket;

onSocketOpen() {}
onReciveMsg() {}
onSocketClose1() {}
onSocketError() {}

start() {
    let url = "ws://192.168.0.85:32167";
    console.log("01")
    this.socket = new WebSocket(url);
    console.log("11")

    this.socket.binaryType = "arraybuffer";
    console.log("21")
    this.socket.onopen = this.onSocketOpen.bind(this);
    console.log("31")
    this.socket.onmessage = this.onReciveMsg.bind(this);
    console.log("41")
    this.socket.onclose = this.onSocketClose1.bind(this);
    console.log("51")
    this.socket.onerror = this.onSocketError.bind(this);
}
2赞

WebSocket 用法在android上有什么需要特别注意的吗?

人工顶置一下,希望有大神提供一个解决思路。
按照官方文档来,标准的websocket,应该只需要简单的new一下就可以了,当前做一个纯websocket测试:android找不到websocket,谷歌浏览器测试却是正常的

自己解决了,来留个爪,项目设置–功能裁剪–网络模块没勾选,勾上就对了
话说没勾websocket网页可以网络连接,安卓不能连接也是无语

5赞

WebSocket 是网页的基础模块,在发布为网页时,直接用的环境提供的WebSocket,不由引擎决定。

而原生项目,不一定会用到WebSocket,因此默认是关闭的。 需要开启。

1赞

了解了,谢谢

感谢,查了半天用你这个方式解决了!