天天看点

【微信小游戏】CocosCreator做小游戏 — WebSocket在真机上无法连接服务器

问题描述:正常使用new WebSocket(url)创建的socket连接,在web和微信开发工具上都是用正常,但在真机上连不上服务器。

解决办法:使用微信提供的socket接口创建连接。

// data: {url, onopen, onclose, onerror, onmessage}
this.createWxSocket = function (data) {
    let soc = wx.connectSocket({
        url: data.url,
        success: function () {
            console.log("connect socket success.");
        },
        fail: function () {
            console.log("connect socket fail.");
        },
    });
    soc.onOpen(function (res) {
      if (data.onopen) data.onopen(res);
    });
    soc.onClose(function (res) {
      if (data.onclose) data.onclose(res);
    });
    soc.onError(function (res) {
      if (data.onerror) data.onerror(res);
    });
    soc.onMessage(function (res) {
      if (data.onmessage) data.onmessage(res);
    });
    return soc;
};
           
if (cc.sys.platform == cc.sys.WECHAT_GAME) {
    _socket = createWxSocket({
        url: url,
        onopen: this._onopen.bind(this),
        onerror: this._onerror.bind(this),
        onmessage: this._onmessage.bind(this),
        onclose: this._onclose.bind(this),
    });
} else {
    _socket = new WebSocket(url);
    _socket.onopen = this._onopen.bind(this);
    _socket.onerror = this._onerror.bind(this);
    _socket.onmessage = this._onmessage.bind(this);
    _socket.onclose = this._onclose.bind(this);
}