forked from nodebooks/socketio-openshift-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
78 lines (60 loc) · 1.98 KB
/
client.js
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
// Use the Singleton pattern
// to make sure that only one Client object exists
var Client;
(function () {
var instance;
Client = function Client() {
if (instance) {
return instance;
}
// Set the instance variable and return it onwards
instance = this;
// Connect websocket to Server
this.connect();
console.log("Client started");
};
}());
Client.prototype.connect = function() {
var connString = config.protocol + config.domain + ':' + config.clientport;
console.log("Websocket connection string:", connString, config.wsclientopts);
var self = this;
this.socket = io.connect(connString, config.wsclientopts);
// Handle error event
this.socket.on('error', function (err) {
console.log("Websocket 'error' event:", err);
});
// Handle connection event
this.socket.on('connect', function () {
console.log("Websocket 'connected' event with params:", self.socket);
document.getElementById('top').innerHTML = "Connected.";
});
// Handle disconnect event
this.socket.on('disconnect', function () {
console.log("Websocket 'disconnect' event");
document.getElementById('top').innerHTML = "Disconnected.";
});
// OWN EVENTS GO HERE...
// Listen for server hello event
this.socket.on('hello', function (data) {
console.log("Server says:", data.greeting);
// Start heartbeat timer
self.heartbeat(self);
});
// pong to our ping
this.socket.on('pong', function (data) {
if(data.id == self.pingtime) {
document.getElementById('ping').innerHTML = Date.now() - self.pingtime + " ms";
}
else {
console.log("pong failed:", data.id, self.pingtime);
}
});
};
// Keep pinging and ponging with server
Client.prototype.heartbeat = function (self) {
// Create heartbeat timer,
// the third param 'self' is not supported in IE9 and earlier
var tmo = setTimeout(self.heartbeat, config.heartbeattmo, self);
self.pingtime = Date.now();
self.socket.emit('ping', {id: self.pingtime});
};