var d1 = new Date();
// wait for response
var d2 = new Date();
var result = d2 - d1;
(function(window) {
var socket = new WebSocket('ws://thelifelessone.dyndns.org:1024/');
var input = document.getElementById('input');
var output = document.getElementById('output');
var msgCounter = 0;
var ping;
setInterval(function() {
msgCounter--;
}, 2000);
socket.onopen = function(e) {
output.innerText += 'Connected.\n';
}
socket.onmessage = function(e) {
var dJSON = JSON.parse(e.data);
ping = (dJSON.timestamp - Date.now());
console.log(Math.abs(ping));
if (dJSON.content != undefined) {
output.innerText += dJSON.id + ': ' + dJSON.content + '\n';
}
window.scroll(0, document.height);
}
input.onkeypress = function(e) {
if (e.keyCode == 13) {
if (input.value != '') {
switch(input.value) {
case ':clear':
output.innerText = '';
input.value = '';
break;
default:
msg = JSON.stringify({'timestamp': Date.now(), 'content': input.value});
if (msgCounter != 5) {
msgCounter++;
socket.send(msg);
}
input.value = '';
break;
}
}
}
}
})(window);
// Requires Node.js with websocket-server.
var ws = require("websocket-server");
var server = ws.createServer();
server.addListener("connection", function(connection){
console.log('Connection established. ID ' + connection.id + ' assigned.');
connection.send(JSON.stringify({'id': connection.id}));
connection.addListener('close', function(e) {
console.log('Client ID ' + connection.id + ' has disconnected.');
});
connection.addListener("message", function(msg){
msg = JSON.parse(msg);
console.log(msg.timestamp);
switch(msg) {
case ':clear':
break;
default:
connection.send(JSON.stringify({
'id': connection.id,
'content': msg.content,
'timestamp': msg.timestamp
}));
connection.broadcast(JSON.stringify({
'id': connection.id,
'content': msg.content
}));
break;
}
});
});
server.listen(1024);
console.log('Listening on port 1024');