首页 > 代码库 > websocket业务代码

websocket业务代码

需求

用户登陆后,服务器实时推送用户的订单提醒,用websocket处理。

技术分享

 

方案

两个js,notify-socket.js处理socket的连接,和socket的处理。

nofify.js,做右下角弹窗处理,用到了layui的弹窗组件。

 

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 = http://www.mamicode.com/data.data;"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="http://www.mamicode.com/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="http://www.mamicode.com/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;});

  

websocket业务代码