比较来自两个WebSocket的实时数据

时间:2018-10-05 12:35:50

标签: node.js websocket

我只是发现websockets和node js,但试图弄清楚如何执行以下操作。我想比较两个不同websocket的值。

const WebSocket = require('ws');

const ws = new WebSocket('wss://1');
const w = new WebSocket('wss://2')

ws.on('message', function incoming(data) {

  var myval1= JSON.parse(data);


});

w.on('message', function incoming(data) {

  var myval2= JSON.parse(data);


});

var whatIwant =  myval1 - myval2;

如何继续比较myva1和myval2?

我曾尝试将第二个on消息调用放在第一个消息中,但是每次调用第一个消息时它都会开始循环,并在几次消息调用后触发断路器。

2 个答案:

答案 0 :(得分:2)

虽然ZeekHuge是正确的,但我们需要记住范围-我们还必须考虑websocket的异步特性-我们只有在收到消息后才能进行比较。每次收到消息以比较该值时,都可以调用一个辅助方法。

public function add($customerid = null)
    {
        $customerServiceType = $this->CustomerServiceTypes->newEntity();
        if ($this->request->is('post')) {
            $customerServiceType = $this->CustomerServiceTypes->patchEntity($customerServiceType, $this->request->getData());
            if ($this->CustomerServiceType->addCustomerServiceType($this->request->data)) {
                $this->Flash->success(__('The customer service type has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The customer service type could not be saved. Please, try again.'));
        }
        $customers = $this->CustomerServiceTypes->Customers->find('list', ['limit' => 200]);
        $serviceTypes = $this->CustomerServiceTypes->ServiceTypes->find('list', ['limit' => 200]);
        $this->set(compact('customerServiceType', 'customers', 'serviceTypes'));
    }

答案 1 :(得分:1)

要能够比较2个网络套接字中的变量,您将必须保存其中一个变量必须在“更大”范围内(至少在给定示例中,因为不涉及数据库) )。以您的代码为例:

const WebSocket = require('ws');

const ws = new WebSocket('wss://1');
const w = new WebSocket('wss://2')

var myval1 = null;
var myval2 = null;
ws.on('message', function incoming(data) {

  myval1= JSON.parse(data);


});

w.on('message', function incoming(data) {

  myval2= JSON.parse(data);


});

var whatIwant =  myval1 - myval2;

请注意,您的代码中还有更多重要的事情要考虑:

  • var whatIwant...将在此脚本运行后立即执行,并且不会使消息到达。

编辑

为了能够在每次收到消息时比较值,可以执行以下操作。

const WebSocket = require('ws');

const ws = new WebSocket('wss://1');
const w = new WebSocket('wss://2')

var w_val = null;
var ws_val = null;
ws.on('message', function incoming(data) {

    ws_val = JSON.parse(data);
    if (w_val !== null ) {
        var comp = ws_val - w_val;
        w_val = null;
        ws_val = null;
    }


});

w.on('message', function incoming(data) {

    w_val = JSON.parse(data);
    if (ws_val !== null ) {
        var comp = ws_val - w_val;
        ws_val = null;
        w_val = null;
    }


});