客户端通过Websocket向Server发送消息不起作用

问题描述 投票:0回答:2

我有一个客户端,它监听两个传感器变量并连接到websocket服务器。要通过以下实现发送到websocket服务器的这些传感器变量的值:

const ws = new WebSocket("ws://" + host + port);
console.log('sent');

ws.onopen = function (event) {
  //listening to sensor values
  monitoredItem1.on("changed",function(dataValue){      
    ws.send(JSON.stringify(" rotation ", dataValue.value.value));
    //console.log('sent');
    console.log(" % rotation = ", (dataValue.value.value).toString());
  });

  //listening to sensor values
  monitoredItem2.on("changed",function(dataValue){
    console.log(" % pressure = ", dataValue.value.value);
    ws.send(JSON.stringify(" pressure ", dataValue.value.value));
    //console.log('sent');
  });
};

服务器看起来像这样:

var Server = require('ws').Server;
var port = process.env.PORT || 8081;
var ws = new Server({port: port});

ws.on("connection", function(w) {
 w.on('message', function(msg){
  console.log('message from client', msg);
 });
});

但是服务器的输出是这样的:

message from client " rotation "
message from client " pressure "
message from client " pressure "
message from client " pressure "
message from client " pressure "
message from client " pressure "
message from client " rotation "
message from client " rotation "
message from client " pressure "

为什么websocket服务器没有收到号码?即使我将dataValue.value.value字符串化它也不起作用?不知道怎么解决这个问题?

谢谢

javascript websocket sensor
2个回答
2
投票

您似乎没有正确访问JSON对象,但我不知道您的JSON结构提供您的JSON数据的示例。

当使用JSON时,两个值如ws.send(JSON.stringify(" rotation ", dataValue.value.value));。它只会在输出中对" rotation "部分进行字符串化。

但是,假设您的数据设置如下。这是你可以访问它的方式。

const data = {
    pressure: 'value-pressure',
    rotation: 'value-rotation',
    embed: {
        value: 'value-embed'
    }

};

console.log(data.pressure); // value-pressure
console.log(data.rotation); // value-rotation
console.log(data.embed.value) // value-embed

您总是可以在发送之前使用toString()将其转换为字符串,然后在接收到JSON之后使用JSON.parse将其重新转换为JSON。

我做了这个小例子来测试使用JSON.stringify(),它发送它,只是不知道你的数据格式。通过Web套接字发送JSON,然后访问该对象。

const WebSocket = require('ws')
var Server = require('ws').Server;
var port = process.env.PORT || 3000;
var ws = new Server({port: port});

ws.on("connection", function(w) {
    w.on('message', function(msg){
        let data = JSON.parse(msg);
        console.log('Incoming', data.pressure); // Access data.pressure value
    });
});

并发送

const WebSocket = require('ws')
const ws = new WebSocket("ws://localhost:3000");
console.log('sent');

ws.onopen = function (event) {
    let data = {
        pressure: 'value',
        rotation: 'rotation',
    };
    ws.send(JSON.stringify(data)) // Send all the data
};

0
投票

尝试使用{}围绕将使其成为JS对象的数据,并且json.stringify()只接受一个参数doc here作为要转换的值,第一个参数就是为什么只有“压力”被转换和发送。

 ws.send(JSON.stringify({"pressure": dataValue.value.value}));
© www.soinside.com 2019 - 2024. All rights reserved.