Blame view

public/js/service/chat/socket-chat.js 1.57 KB
1 2 3 4 5 6 7
/**
 * socket 聊天
 *
 * @author: liqi <qi.li@yoho.cn>
 * @date: 2016/11/8
 */
lijing authored
8
let param,
9 10 11
    servers,
    socket,
    server,
陈轩 authored
12
    sendFailCallback,
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
    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);
陈轩 authored
34
        window.socket = socket = new WebSocket(server + '/im?param=' + param);
35 36 37 38 39 40 41 42 43
        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');
        };
陈轩 authored
44 45 46 47
        socket.onerror = options.onError || function() {
            console.log('websocket meet error');
        };
        sendFailCallback = options.sendFailCallback || $.noop;
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    } 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 {
陈轩 authored
64
        sendFailCallback();
65 66 67 68 69
    }
}

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