客户端通过 Websocket 向服务器发送消息不起作用

Client sending message to Server over Websocket does not work

我有一个客户端,它监听两个传感器变量并连接到一个 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 字符串化,它也不起作用?知道如何解决这个问题吗?

谢谢

您似乎没有正确访问 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.parse 将其重新转换为 JSON 以访问 JSON。

我用JSON.stringify()做了这个小例子来测试,它发送了,只是不知道你的数据格式。通过网络套接字发送一个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
};

尝试在数据周围使用 {} 使其成为 JS 对象,并且 json.stringify() 只接受一个参数 doc here 作为要转换的值,这就是为什么只有第一个参数"pressure " 正在转换和发送。

 ws.send(JSON.stringify({"pressure": dataValue.value.value}));