mauricioSanchez
mauricioSanchez

Reputation: 366

Trying to send a message using Websockets (ws) with Node.js

I'm trying to send a message to my clients when two time stamps are equal, here is the code for the socket part:

var WebSocketServer = require('ws').Server;
wss = new WebSocketServer({
port: WS_PORT
});
var futureTime = new Date(Date.UTC(2014, 3, 10, 4, 2, 0));
var futureTimeMins = futureTime.getMinutes();

wss.on('connection', function (ws) {
 ws.on('message', function (message) {
    // console.log('received: %s', message);
});
 setInterval(checkTime, 1000);
});

function checkTime() {
// console.log("checking time!");
 var date = new Date();
 currentMinutes = date.getMinutes();
 if (currentMinutes == futureTimeMins) {
    var message = {
        "background-color": "red"
    };
    ws.send(JSON.stringify(message));
    console.log("Message was sent");
 } else {
    console.log("Message wasn't sent");
    console.log(currentMinutes);
 }
}

So I want to compare two time stamps, that's why I'm using my function with the setInterval, so that it can check when the time has changed. Once the times have matched I get the following error:

ws.send(JSON.stringify(message));
    ^
ReferenceError: ws is not defined

What I don't understand is that if I'm loading my checktime function inside the scope of function (ws), why doesn't it recognize. I'm new to websockets, so any suggestions are more than welcome

Upvotes: 1

Views: 4361

Answers (1)

Nikolay Lukyanchuk
Nikolay Lukyanchuk

Reputation: 874

Changes

setInterval(function(){ 
    checkTime(ws) },
1000);

function checkTime(ws) {
   ...
}

you use closure (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures) to declare variable ws, but your function checkTime knows nothing about ws, it is predefined function wrapped into setInterval with it's own variavble scope. If you change checkTime declaration to anonymous declaration it will be work.

Upvotes: 2

Related Questions