socket-chat.js
1.29 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
/**
* 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
};