This repository has been archived by the owner on Mar 20, 2021. It is now read-only.
/
client.js.go
120 lines (94 loc) · 2.63 KB
/
client.js.go
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package dispatcher
var ClientJs = []byte(`var Dispatcher = (function () {
var conf = {
onJoin: null,
onLeve: null,
handlers: {},
roomHandlers: {},
conn: null
};
function Dispatcher(endpoint) {
conf.conn = new WebSocket(endpoint);
conf.conn.onmessage = function (msg) {
var data = JSON.parse(msg.data);
if (data.s === true) {
if (data.e == "broadcast") {
if (conf.roomHandlers.hasOwnProperty(data.m.r)) {
conf.roomHandlers[data.m.r](data.m.m);
}
}
} else {
if (conf.handlers.hasOwnProperty(data.e)) {
conf.handlers[data.e](data.m);
}
}
};
}
Dispatcher.prototype.OnConnect = function (cb) {
conf.conn.onopen = cb;
};
Dispatcher.prototype.OnDisconnect = function (cb) {
conf.conn.onclose = cb;
};
Dispatcher.prototype.OnJoin = function (cb) {
conf.onJoin = cb;
};
Dispatcher.prototype.OnLeve = function (cb) {
conf.onLeve = cb;
};
Dispatcher.prototype.Emit = function (event, message) {
msg = {
e: event,
s: false,
m: message
};
conf.conn.send(JSON.stringify(msg));
};
Dispatcher.prototype.EmitTo = function (recipient, event, message) {
msg = {
e: "emitTo",
s: true,
m: {
e: event,
r: recipient,
m: message
}
};
conf.conn.send(JSON.stringify(msg));
};
Dispatcher.prototype.Broadcast = function (room, message) {
msg = {
e: "broadcast",
s: true,
m: {
r: room,
m: message
}
};
conf.conn.send(JSON.stringify(msg));
};
Dispatcher.prototype.On = function (event, cb) {
conf.handlers[event] = cb;
};
Dispatcher.prototype.Join = function (room, cb) {
conf.roomHandlers[room] = cb;
msg = {
e: "join",
s: true,
m: room
};
conf.conn.send(JSON.stringify(msg));
};
Dispatcher.prototype.Leave = function (room) {
msg = {
e: "leave",
s: true,
m: room
};
conf.conn.send(JSON.stringify(msg));
};
Dispatcher.prototype.Disconnect = function () {
conf.conn.close();
};
return Dispatcher;
} ());`)