Repository navigation
Expand file tree
/
Copy pathclient.js
More file actions
118 lines (103 loc) · 2.44 KB
/
Copy pathclient.js
File metadata and controls
118 lines (103 loc) · 2.44 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
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
function Client(address) {
Log('client', 'creating');
this.socket = null;
this.connected = false;
try {
this.socket = new WebSocket(address);
} catch(error) {
this.socket = null;
}
if (!this.socket) {
try {
this.socket = new MozWebSocket(address);
} catch(error) {
this.socket = null;
}
}
if (this.socket) {
this.socket.link = this;
Log('client', 'created');
this.OnConnect = null;
this.OnTimeout = null;
this.OnDisconnect = null;
this.callbacks = new Object();
this.Trigger = function(packet) {
if (this.callbacks[packet.type]) {
if (packet.type !== 'userUpdate' &&
packet.type !== 'mapData' &&
packet.type !== 'heroUpdate' &&
packet.type !== 'charUpdate' &&
packet.type !== 'heroRemove') {
Log('packet', 'received: ' + JSON.stringify(packet));
}
for(var i in this.callbacks[packet.type]) {
this.callbacks[packet.type][i](packet);
}
} else {
LogW('packet', 'unatached event for packet: ' + JSON.stringify(packet));
}
}
this.socket.onopen = function() {
LogW('client event', 'onopen');
this.link.connected = true;
if (this.link.OnConnect) {
this.link.OnConnect();
}
}
this.socket.onclose = function(data) {
LogW('client event', 'onclose');
if (this.link.connected) {
if (this.link.OnDisconnect) {
this.link.OnDisconnect();
}
} else {
if (this.link.OnTimeout) {
this.link.OnTimeout();
}
}
this.link.connected = false;
}
this.socket.onerror = function(data) {
LogE('client event', 'onerror');
if (this.link.connected) {
if (this.link.OnDisconnect) {
this.link.OnDisconnect();
}
} else {
if (this.link.OnTimeout) {
this.link.OnTimeout();
}
}
}
this.socket.onmessage = function(event) {
var packet = null;
try {
packet = new Packet(JSON.parse(event.data));
} catch(error) {
LogE('packet', 'error parsing JSON: ' + event.data);
}
if (packet != null) {
if (packet.type) {
this.link.Trigger(packet);
} else {
LogW('packet', 'type is not defined: ' + event.data);
}
}
}
} else {
LogE('client', 'websockets not supported');
}
}
Client.prototype.Send = function(data) {
if (this.socket) {
this.socket.send(data);
}
}
Client.prototype.AddCallBack = function(name, func) {
if (this.socket) {
if (!this.callbacks[name]) {
this.callbacks[name] = new Array();
}
this.callbacks[name].push(func);
}
}