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

var param,
    servers,
    socket,
    server,
    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);
        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');
        };
    } else {
        console.log('websocket is not support');
    }
}

/**
 * 发送消息
 * @param msg 消息内容
 */
function sendMsg(msg) {
    if (!window.WebSocket) {
        return;
    }
    if (socket.readyState === WebSocket.OPEN) {
        console.log(msg);
        socket.send(msg);
    } else {
        console.log('The socket is not open.');
    }
}

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