websocket实践小结

    本次在项目中,需要制作一个客服与顾客进行对话的消息界面,所以采用了webSocket进行双方间交流时的数据传递。话不多说直接上代码:

// 创建socket
function createWebSocket() {
    const wsUrl = "ws://";
    try {
        ws = new WebSocket(wsUrl);
        init();
    } catch (e) {
        console.log('catch');
        reconnect();
    }
}
var lockReconnect = false; // 避免重复连接的标识
// 重新连接socket
function reconnect() {
    if (lockReconnect) return;
    lockReconnect = true;
    var tt
    tt && clearTimeout(tt);
    tt = setTimeout(function () { // 没连接上会一直重连,设置延迟避免请求过多
        createWebSocket();
        lockReconnect = false;
    }, 4000);
}
// 初始化socket
function init() {
    ws.onclose = function () {  //     连接关闭时触发
        console.log('链接关闭');
        reconnect();
    };
    ws.onerror = function () { // 通信发生错误时触发
        console.log('发生异常了');
        reconnect();
    };
    ws.onopen = function () { // 连接建立时触发
        var obj = {        //心跳检测重置
            'to': customer_id,
            'form': kefu_id,
            'type': '-1',
            'content': $('#sendText').val()
        };
        ws.send(JSON.stringify(obj));
        heartCheck.start();
    };
    ws.onmessage = function (event) {  //拿到任何消息都说明当前连接是正常的
        console.log('接收到消息');
        getChatEvent(JSON.parse(event.data));
        heartCheck.start();
    }
}
// 心跳检测
var heartCheck = {
    timeout: 3000,
    timeoutObj: null,
    serverTimeoutObj: null,
    start: function () {
        console.log('start');
        var self = this;
        console.log(this.timeoutObj)
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function () { //这里发送一个心跳,后端收到后,返回一个心跳消息,  
            if (ws.readyState == 1) { //onmessage拿到返回的心跳就说明连接正常
            } else { //否则重连
                reconnect();
            }
        }, this.timeout)
    }
};

客服这边的发送事件代码如下:

// 发送事件
function sendMsgBtn() {
    heartCheck.start();
    var obj = {
        'to': customer_id,
        'form': kefu_id,
        'type': '1',
        'content': $('#sendText').val(),
    };
    console.log(obj.content)
    ws.send(JSON.stringify(obj));
    msg_html_arr[customer_index - 1]['msg'] += `
    <p class="time"><span>${getCurrentDate()}</span></p>
    <div class="chatout">
        <img src="../img/kefu.jpg">
        <span>${$('#sendText').val()}</span>
    </div>`;
    $('#sendText').val('');
    setHTMLEvent();
}

顾客的接收事件的代码:

// 接收事件
function setChatEvent(item) {
    returnHTML();
    if (!customer_index) { // 尚未进行过对话
        let msg_html = '';
        item.message.forEach((item_) => {
            msg_html += `
            <p class="time"><span>${item_.created_at}</span></p>
            <div class="chatin">
                <img src="${item.headimg}">
                <span>${item_.words}</span>
            </div>`;
        });
        msg_html_arr.push({
            name: customer_id,
            msg: msg_html
        });
    }
    returnHTML();
    setHTMLEvent();
}

实时获取到返回的数据代码:

// 实时获取返回信息
function getChatEvent(data) {
    if (data.type !== '1') return;
    msg_html_arr[customer_index - 1]['msg'] += `
    <p class="time"><span>${getCurrentDate()}</span></p>
    <div class="chatin">
        <img src="${cust_img}">
        <span>${data.content}</span>
    </div>`;
    setHTMLEvent();
}

效果图:

猜你喜欢

转载自www.cnblogs.com/hxw1024/p/12023983.html