美文网首页
使用QQ玩一玩 brickEngine 中的websocket

使用QQ玩一玩 brickEngine 中的websocket

作者: VIL凌霄 | 来源:发表于2019-11-14 11:37 被阅读0次

    在使用 QQ玩一玩的websocket 时找不到纤细的使用说明文档,这里给一份适配好的代码。

    function  VilWebSocket(){ 
        var mCallBack = callback;
        var mHost = host;
        var socketMsgQueue = [];
        var socketOpen = false;
        var socket = new BK.WebSocket(host);
        var that = this;
    
        this.send = function (msg) {
            if(socketOpen){
                socket.send(msg.buffer)
            }else{
                if (socketMsgQueue.length < 100) {
                    socketMsgQueue.unshift(msg);
                }
            }
        };
    
        this.close = function () {
            console.log("websocket close");
            if(socket){
                socket.close()
            }
        };
    
        socket.onOpen = function(res) {
            socketOpen = true;
            console.log("[BK.WebSocket][connect]:" ,res);
            while (socketMsgQueue.length > 0) {
                that.send(socketMsgQueue.pop());
            }
            mCallBack.onConnect && mCallBack.onConnect(mHost);
        };
    
        socket.onClose = function(res) {
            socketOpen = false;
            console.log("[BK.WebSocket][onClose] case:",JSON.stringify(res));
            var e = {code:1000, message:" close normal"};
            mCallBack.onDisConnect && mCallBack.onDisConnect(mHost, e);
        };
    
        socket.onError = function(err){
            if(socket && socketOpen){
                socketOpen = false;
                socket.close();
            }
            var e = {code:err.getErrorCode(), message: err.getErrorString()};
            if(e.code === 65535){
                e.code = 1000;
            }
            mCallBack.onDisConnect && mCallBack.onDisConnect(mHost,e);
        };
    
        socket.onMessage = function (res, data) {
            var buf = data.data;
            buf.rewind();
            var ab = new ArrayBuffer(buf.length);
            var dataView = new DataView(ab);
            while (!buf.eof) {
                dataView.setUint8(buf.pointer, buf.readUint8Buffer());
            }
            mCallBack.onMsg && mCallBack.onMsg(dataView);
        };
    
        if(socket){
            socket.connect()
        }
    }
    
    

    相关文章

      网友评论

          本文标题:使用QQ玩一玩 brickEngine 中的websocket

          本文链接:https://www.haomeiwen.com/subject/gurqtqtx.html