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

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

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,所以任何build议都比欢迎

变化

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

你使用闭包 (请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures )来声明variablesws,但是你的函数checkTime对ws一无所知,它被预定义的函数包装成了setInterval有自己的可变范围。 如果您将checkTime声明更改为匿名声明,它将是工作。