尝试使用带有Node.js的Websockets(ws)发送消息

时间:2014-04-09 04:20:49

标签: javascript node.js websocket

当两个时间戳相等时,我正在尝试向我的客户发送消息,这是套接字部分的代码:

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);
 }
}

所以我想比较两个时间戳,这就是为什么我在setInterval中使用我的函数,以便它可以检查时间的变化。一旦时间匹配,我得到以下错误:

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

我不明白的是,如果我在功能范围(ws)中加载我的checktime函数,为什么它不能识别。我是websockets的新手,所以任何建议都非常受欢迎

1 个答案:

答案 0 :(得分:2)

更改

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

function checkTime(ws) {
   ...
}

你使用闭包(参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures)来声明变量ws,但你的函数checkTime对ws一无所知,它是包含在setInterval中的预定义函数,它具有自己的可变范围。如果将checkTime声明更改为匿名声明,它将起作用。