我有一个node.js服务器,它通过websocket从“昏昏欲睡”的客户机获取数据,然后尝试通过websocket将数据推送到web客户端。昏昏欲睡意味着它睡上几分钟,然后醒来测量数据,然后再睡觉。见下文:
困倦的客户端-> websocket -> node.js服务器->websocket-> web客户端
只有一个昏昏欲睡的客户端,但是可以有多个web客户端。所以当新的数据到达时,我需要把它推到所有的网络客户端网络套接字。为了跟踪这一点,我有一个数组跟踪网络客户端和存储他们的ctx信息供以后使用。
但是,这就是问题所在,当我试图将数据推送到web客户端websocket时,我会得到一个上下文错误和node.js崩溃。
这是我的代码:
var globalCtx = [];
app.ws.use( function( ctx, next ) {
ctx.websocket.on('message', function ( message )
{
if( "telemetry" in jsonMsg )
{
console.log( "Got Telemetry: " );
console.log( message.toString() );
// we just got a telemetry message,
// so push it to the all the web client websockets
globalCtx.forEach( (myCtx, next) => {
console.log( "DEBUG: ", util.inspect(myCtx) ); <<<-----crashes here
myCtx.send( jsonMsg ); <<<----- or crashes here when not debugging
});
}
else
if( "webClient" in jsonMsg )
{
console.log( "Got WS Client: " );
console.log( message.toString() );
// we just got a web client connection message
// so store its context for pushing to later
if( Array.isArray( globalCtx ) && globalCtx.length )
{
// search for an existing entry
for( let idx = 0; idx < globalCtx.length; idx++ )
{
if( globalCtx[ idx ].ip == ctx.ip )
{
// we already have this IP stored, do nothing
console.log("IP already found: ", ctx.ip );
//return next( ctx );
return;
}
}
// we made it here, this means that the IP wasn't found
console.log("not found, adding IP: ", ctx.ip );
globalCtx.push( ctx );
}
else
{
// the array is empty, so just add it
console.log("empty array adding IP: ", ctx.ip );
globalCtx.push( ctx );
}
}
});
return next(ctx);
});以下是错误:
/home/pi/node_modules/koa/lib/response.js:73
return this.res.statusCode;
^
TypeError: Cannot read property 'statusCode' of undefined
at Object.get status [as status] (/home/pi/node_modules/koa/lib/response.js:73:21)
at /home/pi/node_modules/only/index.js:6:20
at Array.reduce (<anonymous>)
at module.exports (/home/pi/node_modules/only/index.js:5:15)
at Object.toJSON (/home/pi/node_modules/koa/lib/response.js: 562:12)
at Object.toJSON (/home/pi/node_modules/koa/lib/context.js:5 1:31)
at Object.inspect (/home/pi/node_modules/koa/lib/context.js: 33:17)
at formatValue (internal/util/inspect.js:745:19)
at Object.inspect (internal/util/inspect.js:319:10)
at /home/pi/koaThermostat/index2.js:46:46以下是myCtx.send( jsonMsg );行中的错误
/home/pi/koaThermostat/index2.js:47
myCtx.send( jsonMsg );
^
TypeError: myCtx.send is not a function
at /home/pi/koaThermostat/index2.js:47:23发布于 2022-08-26 03:41:54
我觉得很傻!在websocket中使用Koa上下文时,必须使用websocket对象。因此,在我的例子中,应该是myCtx.websocket.send()而不是myCtx.send()。现在我的下一个窃听器..。
https://stackoverflow.com/questions/73452968
复制相似问题