socket-chat.js 1.57 KB
/**
 * socket 聊天
 *
 * @author: liqi <qi.li@yoho.cn>
 * @date: 2016/11/8
 */

let param,
    servers,
    socket,
    server,
    sendFailCallback,
    conversationMessage;

function _randomServer() {
    return servers[new Date().getTime() % servers.length];
}

/**
 * socket初始化
 * @param options
 */
function socketInit(options) {
    servers = options.servers;
    server = _randomServer();
    conversationMessage = options.conversationMessage;

    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }

    if (window.WebSocket) {
        param = JSON.stringify(conversationMessage);
        window.socket = socket = new WebSocket(server + '/im?param=' + param);
        socket.onmessage = options.onMessage || function() {
            console.log('received msg');
        };
        socket.onopen = options.onOpen || function() {
            console.log('websocket is open');
        };
        socket.onclose = options.onClose || function() {
            console.log('websocket is closed');
        };
        socket.onerror = options.onError || function() {
            console.log('websocket meet error');
        };
        sendFailCallback = options.sendFailCallback || $.noop;
    } else {
        console.log('websocket is not support');
    }
}

/**
 * 发送消息
 * @param msg 消息内容
 */
function sendMsg(msg) {
    if (!window.WebSocket) {
        return;
    }
    if (socket.readyState === WebSocket.OPEN) {
        socket.send(msg);
    } else {
        sendFailCallback();
    }
}

module.exports = {
    init: socketInit,
    send: sendMsg,
};