socket-chat.js
1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* 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,
};