与Nodejs Websocket同步发送消息

时间:2019-01-22 02:08:03

标签: node.js websocket

我的应用程序包含三个模块:

  1. WebSocket模块:驻留在远程服务器(互联网)上,并充当Websocket 客户端模块和客户端模块之间建立连接的服务器 Webhook模块。
  2. Webhook模块:驻留在远程服务器(互联网)上,它充当 一个Webhook来回答用户的HTTP发布请求。它也通过websocket连接到Websocket模块。
  3. 客户端模块:驻留在我的本地计算机上,并且已连接到 的     通过websocket的Webhook模型。此客户负责获取查询     从我的本地后端开始。

当用户通过HTTP Post请求调用Webhook模块时,Webhook模块将通过websocket启动与WebSocket模块的连接。然后,WebSocket模块启动与客户端模块的连接,并使用必要的信息进行响应。实际上,我必须这样做以消除在公司中被阻止的HTTP隧道。

问题是,当我打开两个浏览器窗口以同时使用不同的参数(例如,参数“ A”)执行HTTP Post请求 时,我希望获得参数“ B”的返回“ A”,我希望得到“ B”而不是“ A”。但是我的代码/设计有问题。如果我同时执行,则抛出“ A”,然后得到“ B”,这是错误的。我该如何克服这个问题。

这是一个简单的图来说明它。 enter image description here

WebSocket模块

'use strict'

//This is WebSocket Server

const clients = {};
const SocketIO = require('socket.io');
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const ws = SocketIO(server);

const port = 3000;

var clientid;

ws.on('connection', (client) => {
  clients[client.id] = client;
  console.log('new connection', client.id);

  clientid = client.id;

  client.emit('message', { message: 'welc' })

  client.on('disconnect', () => {
    delete clients[client.id];
    console.log('Client ' + client.id + ' disconnected. Deleted');
  });

  client.on('WH', function (from, msg) {
    console.log('Message from Webhook', from, ' : ', msg);
    client.broadcast.emit('message', { message: msg });

    //console.log('send to: ' + clientid);
    //ws.to(clientid).emit('hey', { message: msg });

    //client.emit('message', { message: msg })
  });

  client.on('CL', function (from, msg) {
    console.log('Message from Client', from, ' : ', msg);
    client.broadcast.emit('message', 'me', msg);

    //ws.to(client.id).emit('message', 'me', msg);
    //client.emit('message', 'me', msg);
  });


});
server.listen(process.env.PORT || port);
console.log('WebSocket Server is running on port ' + port);

Webhook模块

'use strict'

//This is WebHook Server

const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const http = require('http');
const io = require('socket.io-client');

const app = express()
app.use(bodyParser.json())

const clients = {};
const SocketIO = require('socket.io');
const server = http.createServer(app);
const ws = SocketIO(server);

const port = 5000;

let Res;
let httpreq = false;
let nctid;
let ts;

const socket = io.connect('http://localhost:3000', {reconnect: true});

// Add a connect listener
socket.on('connect', function() {
    console.log('Connected to WebSocket server!');
});


socket.on('message', function(from, msg) {

    //console.log('Message from ', from, ' : ', msg);
    console.log('nctid: ' + nctid + ', ts: ' + ts);

    //Get the message from Client

    if (httpreq) {
        Res.send({
            replies: [{
                type: 'text',
                content: msg,
            }],
            conversation: {
                memory: {
                    key: msg
                }
            }
        })

        httpreq = false;
    }
});

app.listen(process.env.PORT || port, () => {
    console.log('Webhook server is running on port ' + port);
})


app.post('/', (req, res) => {
    //console.log(req.body)

    let query = req.body.nlp.entities.query[0].value;
    nctid = req.body.nlp.entities.nctid[0].value;

    ts =  Math.floor(Date.now() / 1000);

    console.log("query: " + query + '|' + nctid + '|' + ts);

    //Send message to WebSocket server with parameter query and NCTID

    socket.emit('WH', 'me', query + '|' + nctid);
    Res = res;
    httpreq = true;
})

app.post('/errors', (req, res) => {
    console.log(req.body);
    res.send();
})

客户端模块

'use strict'

//This is client app running on client premise

const request = require('request');
const parser = require('xml2json');
const io = require('socket.io-client');
const socket = io.connect('http://localhost:3000', {reconnect: true});

// Add a connect listener
socket.on('connect', function(socket) {
    console.log('Connected to WebSocket server!');
});

socket.on('message', function(from, msg) {
    //console.log('MSG', from, ' : ', msg);
    console.log(from);
    let param = from.message.split('|');
    let query = param[0];
    let nctid = param[1];


    if (typeof nctid != 'undefined') {
        getNCTID(nctid, function(returnValue) {
            //console.log(returnValue);
            try {
                let json = parser.toJson(returnValue);
                json = JSON.parse(json);

                if (query == 'title')
                    socket.emit('CL', 'me', 'Title is ' + json.clinical_study.brief_title);
                else
                    socket.emit('CL', 'me', 'Status is ' + json.clinical_study.overall_status);

            } catch (e) {
                console.log(e);
                socket.emit('CL', 'me', 'No NCTID ' + nctid);
            }
        });
    }
});


function getNCTID(nctid, callback) {

    let url = "https://clinicaltrials.gov/ct2/show/" + nctid + "?displayxml=true";

    let options = {
        url: url,
        method: 'GET'
    }

    //console.log(options);
    let requestWithEncoding = function(options, callback) {
        let req = request.get(options);

        req.on('response', function(res) {
            let chunks = [];
            res.on('data', function(chunk) {
                chunks.push(chunk);
            });


            res.on('end', function() {
                let buffer = Buffer.concat(chunks);
                let encoding = res.headers['content-encoding'];
                if (encoding == 'gzip') {
                    zlib.gunzip(buffer, function(err, decoded) {
                        callback(err, decoded && decoded.toString());
                    });
                } else if (encoding == 'deflate') {
                    zlib.inflate(buffer, function(err, decoded) {
                        callback(err, decoded && decoded.toString());
                    })
                } else {
                    callback(null, buffer.toString());
                }
            });
        });


        req.on('error', function(err) {
            callback(err);
        });
    }


    requestWithEncoding(options, function(err, data) {
        if (err) {
            console.log('err:' + err);
            callback('error');
        } else
            //console.log(data);
            callback(data);
    })
}

0 个答案:

没有答案