websocket業務代碼

需求

用戶登錄後,服務器實時推送用戶的訂單提醒,用websocket處理。javascript

 

方案

兩個js,notify-socket.js處理socket的鏈接,和socket的處理。html

nofify.js,作右下角彈窗處理,用到了layui的彈窗組件。java

 

notify-socket.js

/**
 * Created by nuanfeng on 2016/9/20.
 */

define(function(require, exports, module) {
    require('jQuery');

    var util = require('util'),
        jsonApi = require('jsonApi'),
        Notify = require('notify');

    var Elems = {

    };

    socketArea = {
        /**
         * 註冊socket身份憑證
         */
        registerSocket: function(){
            var self = this,
                uri = jsonApi.socketRegister;
            console.log('e');
            try {
                util.ajaxFn(uri, {}, function (data) {

                    self.initSocket(data);
                }, function () {
                    setTimeout(function () {
                        console.log("從新註冊socket...");
                        self.registerSocket();
                    }, 5000);
                });
            } catch (e) {
                setTimeout(function () {
                    console.log("從新註冊socket...");
                    self.registerSocket();
                }, 5000);
            }
        },

        /**
         * 心跳事件
         */
        heartBeatEvent: function(socket, data) {
            window.setInterval(function () {
                console.log((new Date()).Format('yyyy-MM-dd hh:mm:ss') + "\t心跳事件....");
                if (socket) {
                    data.dataType = 1000;
                    socket.send(JSON.stringify(data));
                }
            }, 1000 * 60);
        },

        /**
         * 初始化socket
         * @param data
         */
        initSocket: function(data) {
            var self = this;
            var data = data.data;
            var socket = new WebSocket('ws://192.168.10.111:9092/websocket');
            //var socket = new WebSocket('ws://192.168.10.19:9092/websocket');

            //open socket
            socket.onopen = function (event) {
                data.dataType = 1;

                //send a init msg
                socket.send(JSON.stringify(data));

                //listen
                socket.onmessage = function (event) {
                    var data = JSON.parse(event.data);
                    console.log("onmessage -->> ", event);
                    //self.msgHandle(JSON.parse(event.data));
                    var notify = new Notify();
                    notify.showMessage(JSON.parse(event.data));
                };

                socket.onclose = function (event) {
                    console.log("onclose -- >>>於" + new Date(), event);
                }
            }
            self.heartBeatEvent(socket, data);
        },

        /**
         * 處理
         * @param data
         */
        msgHandle: function(data) {
            var self = this;

            if (data.flag == 1) { // success
                switch (data.dataType) {
                    case 1: //註冊
                        self.registerSocketEvent(data);
                        break;
                    case 2: // 支付
                        self.paySocketEvent(data);
                        break;
                    case 3: // 需求
                        self.needSocketEvent(data);
                        break;
                    case 4: // 下單
                        self.orderSocketEvent(data);
                        break;
                    case 5: // 新用戶審覈
                        self.userCheckSocketEvent(data);
                        break;
                    case 6: // 提現
                        self.withDrawSocketEvent(data);
                        break;
                    case 7: // 退款
                        self.refundSocketEvent(data);
                        break;
                    case 0: // default
                        break;
                }
            }
        },

        /**
         * 註冊事件
         * @param data
         */
        registerSocketEvent: function (data) {
            console.log("恭喜,於" + (new Date()).Format('yyyy-MM-dd hh:mm:ss') + "註冊成功...");
        },

        /**
         * 支付事件
         * @param data
         */
        paySocketEvent: function (data) {
            console.log("您有新的訂單已支付...");
            mallMenu.refreshShipStats(true);
        },

        /**
         * 需求事件
         * @param data
         */
        needSocketEvent: function (data) {
            console.log("您有新的需求須要報價...");
            mallMenu.refreshNeedStats(true);
        },

        /**
         * 下單事件
         * @param data
         */
        orderSocketEvent: function (data) {
            console.log("您有新的訂單已生成");
        },

        /**
         * 用戶審覈事件
         * @param data
         */
        userCheckSocketEvent: function (data) {
            console.log("你有新的用戶須要審覈...");
            // TODO: 根據不一樣的data跳轉不一樣的列表頁面
            mallMenu.refreshUserStats(true);
        },

        /**
         * 提現申請事件
         * @param data
         */
        withDrawSocketEvent: function (data) {
            console.log("您有新的提現申請須要處理...");
            mallMenu.refreshFinance(true);
        },

        /**
         * 退款申請事件
         * @param data
         */
        refundSocketEvent: function (data) {
            console.log("您有新的退款申請須要處理...");
            mallMenu.refreshFinanceStats(true);

        }

    };

    module.exports = socketArea;

});

  

notify.js

/**
 * Created by nuenfeng on 2016/9/20.
 */

define(function(require, exports, module) {
    function Notify(params, callback) {
        this.init();
    }

    Notify.prototype.init = function () {
        console.log('notify init...')
    }

    Notify.prototype.showMessage = function(data){
        var msg;
        if (data.dataType==1 || data.dataType==8) {
            //return;
        } else {
            msg = data.data.message;
        }

        var html = '<div class="cont">';
        html += '<p>' + msg + '</p>';
        switch(data.dataType) {
            case 1:
                //html += '<a load="./main-pages/goods/goods-list.html" class="sui-btn btn-primary btn-radius btn-small" id="J_NoticeBtn">當即查看</a>';
                break;
            case 2:
                html += '<a href="/seller/father/orders.html?orderStatus=1" class="sui-btn btn-primary btn-radius btn-small" id="J_NotifyBtn">當即查看</a>';
                break;
            case 4:
                html += '<a href="/seller/father/orders.html?orderStatus=0" class="sui-btn btn-primary btn-radius btn-small" id="J_NotifyBtn">當即查看</a>';
                break;
        }
        html += '</div>';
        layer.open({
            type: 1,
            title: '通知',
            closeBtn: 1,
            shade: [0],
            area: ['340px', '215px'],
            offset: 'rb', //右下角彈出
            time: 5000, //5秒後自動關閉
            content: html,
            shift: 2,
            skin: 'notify-panel',
            move: false
        });
        voicePlay(data.dataType);
    }

    var voicePlay = function(dataType){
        var audio = new Audio("/js/components/notify/voice-newmsg.mp3");
        audio.play();
    }

    module.exports = Notify;
});
相關文章
相關標籤/搜索