Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 这是通过websocket解析传入JSON并根据消息类型做出响应的正确方法吗?_Javascript_Node.js_Json - Fatal编程技术网

Javascript 这是通过websocket解析传入JSON并根据消息类型做出响应的正确方法吗?

Javascript 这是通过websocket解析传入JSON并根据消息类型做出响应的正确方法吗?,javascript,node.js,json,Javascript,Node.js,Json,因此,我使用OCPP1.6JSON通过websocket从chargepoint接收JSON。 我正在尝试使用Node.js解析消息并根据消息的内容做出适当的响应 以下是我收到的信息: [ 2, 'bc7MRxWrWFnfQzepuhKSsevqXEqheQSqMcu3', 'BootNotification', { chargePointVendor: 'AVT-Company', chargePointModel: 'AVT-Express', chargePoi

因此,我使用OCPP1.6JSON通过websocket从chargepoint接收JSON。 我正在尝试使用Node.js解析消息并根据消息的内容做出适当的响应

以下是我收到的信息:

[ 2,
  'bc7MRxWrWFnfQzepuhKSsevqXEqheQSqMcu3',
  'BootNotification',
  { chargePointVendor: 'AVT-Company',
    chargePointModel: 'AVT-Express',
    chargePointSerialNumber: 'avt.001.13.1',
    chargeBoxSerialNumber: 'avt.001.13.1.01',
    firmwareVersion: '0.9.87',
    iccid: '',
    imsi: '',
    meterType: 'AVT NQC-ACDC',
    meterSerialNumber: 'avt.001.13.1.01' } ]
在这种情况下,它是“BootNotification”消息,我需要用“Accepted”消息响应它

这是我的密码:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {

    //Make incoming JSON into javascript object
    var msg = JSON.parse(message)

    // Print whole message to console
    console.log(msg)

    // Print only message type to console. For example BootNotification, Heartbeat etc...
   console.log("Message type: " + msg[2])

    // Send response depending on what the message type is
    if (msg[2] === "BootNotification") {
      //Send correct response

    } // Add all the message types

  });


});
这样,我可以将消息类型作为字符串打印到控制台:

Message type: BootNotification
所以我的问题是,这是获取消息类型的正确方法吗? 我是新手,所以我想确定一下


OCPP1.6JSON的规范可以在这里找到:

我想是的是内置于pares JSON字符串中的。如果出现错误,它会抛出一个错误,因此您可以
尝试/catch
此操作

由于您得到的响应是一个数组,因此没有其他方法可以使用数字索引访问其项


在这种情况下,我个人更喜欢这样:

const handlers = {
  'BootNotification': request => { 'msg': 'what a request' }
};
你可以:

let respone = {'msg': 'Cannot handle this'}

if (handlers.hasOwnProperty(msg[2])) {
  response = handlers[msg[2]](msg);

}

但这正是我要走的路。

我想是的是内置于pares JSON字符串中的。如果出现错误,它会抛出一个错误,因此您可以
尝试/catch
此操作

由于您得到的响应是一个数组,因此没有其他方法可以使用数字索引访问其项


在这种情况下,我个人更喜欢这样:

const handlers = {
  'BootNotification': request => { 'msg': 'what a request' }
};
你可以:

let respone = {'msg': 'Cannot handle this'}

if (handlers.hasOwnProperty(msg[2])) {
  response = handlers[msg[2]](msg);

}
但这正是我要走的路