天天看點

【微信小遊戲】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);
}