From 22ceaf4f83e1253fdd58a7765805d3c7a50fe0a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cyrille=20M=C3=A9dard=20de=20Chardon?= Date: Mon, 2 Sep 2013 20:33:43 +0200 Subject: [PATCH] Updated websocket server so that it sends date-time every five seconds to all clients --- displayclienthtml/websocket_demo/ws_server.js | 30 +++++++++++++++---- displayclienthtml/websocket_demo/ws_test.html | 23 +++++++++----- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/displayclienthtml/websocket_demo/ws_server.js b/displayclienthtml/websocket_demo/ws_server.js index 39f6e6a..c7aeea2 100644 --- a/displayclienthtml/websocket_demo/ws_server.js +++ b/displayclienthtml/websocket_demo/ws_server.js @@ -6,25 +6,26 @@ var http = require('http'); var server = http.createServer(function(request, response) {}); server.listen(1234, function() { - console.log((new Date()) + ' Server is listening on port 1234'); + console.log((new Date()) + ' Server is listening on port 1234'); }); var WebSocketServer = require('websocket').server; wsServer = new WebSocketServer({ - httpServer: server + httpServer: server }); -wsServer.on('request', function(r){ +wsServer.on('request', function(r) { var connection = r.accept('echo-protocol', r.origin); // Specific id for this client & increment count var id = count++; - // // Store the connection method so we can loop through & contact all clients + // Store the connection method so we can loop through & contact all clients clients[id] = connection console.log((new Date()) + ' Connection accepted [' + id + ']'); + clients[id].sendUTF("Welcome to the server. You are connected. This message has been pushed to you."); // Create event listener connection.on('message', function(message) { @@ -41,10 +42,27 @@ wsServer.on('request', function(r){ // Create event listener for close connection.on('close', function(reasonCode, description) { - delete clients[id]; - console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); + delete clients[id]; + console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); }); }); +var sendTime = function () { + var now, i = 0; + + // get time now + now = new Date(); + + // send time to all clients + for(i in clients) { + // Send a message to the client with the message + clients[i].sendUTF(now); + } + + // repeat in 5 seconds + setTimeout(sendTime, 5000); +}; +// every 5 seconds send the date/time +setTimeout(sendTime, 5000); diff --git a/displayclienthtml/websocket_demo/ws_test.html b/displayclienthtml/websocket_demo/ws_test.html index 48fd34d..0d86561 100644 --- a/displayclienthtml/websocket_demo/ws_test.html +++ b/displayclienthtml/websocket_demo/ws_test.html @@ -4,20 +4,28 @@ Web socket test @@ -27,5 +35,6 @@
Received from server:
+