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

var servers,
    socket,
    server,
    conversationMessage;

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

function socketInit(options) {
    var param;

    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');
    }
}

function sendMsg(msg) {
    if (!window.WebSocket) {
        return;
    }
    if (socket.readyState === WebSocket.OPEN) {
        socket.send(msg);
    } else {
        console.log('The socket is not open.');
    }
}

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