Nodejs websocket与外部系统的通信

时间:2014-11-21 19:06:02

标签: node.js websocket ipc

我是nodejs的新手,我正在尝试解决与外部系统的通信问题。

有一个外部系统的网关可以处理端口5000上的websocket请求。在下面的例子中,当你请求主页时,nodejs打开websocket连接,然后在websocket open事件上它发送请求并等待使用的响应用于HTTP响应。

您是否知道如何仅将websocket打开到外部系统一次并根据请求ID处理请求?

var ws = require('ws');
var express = require('express');
var async = require('async');
var uuid = require('node-uuid');

app = express();

app.get('/', function (req, res) {
    var webSocket = new ws('ws://localhost:5000/');
    async.series([
        function (callback) {
            webSocket.on('open', function () {
                webSocket.send(JSON.stringify({query:'data query', requestid: uuid.v4()}));
                callback(null, 'data query');
            });            
        },
        function (callback) {
            webSocket.on('message', function (data, flags) {
                callback(null, data);
            })
        }
    ], function (err, results) {
        res.setHeader('content-type', 'text/javascript');
        res.send(results[1]);
        webSocket.terminate();
    });
});

var server = app.listen(3000, function () {
    var port = server.address().port
    console.log('Listening at %s', port)
});

1 个答案:

答案 0 :(得分:1)

感谢您的提示。我以下面的解决方案结束了我的期望:

var ws = require('ws');
var express = require('express');
var uuid = require('node-uuid');

var requests = {};

app = express();

var webSocket = new ws('ws://localhost:5000/');
webSocket.on('open', function () {
    console.log('Connected!');
});            

webSocket.on('message', function (data, flags) {
    var json = JSON.parse(data);
    console.log(json.requestId);
    var res = requests[json.requestId];
    res.setHeader('content-type', 'text/javascript');
    res.send(json.data);
    delete requests[json.requestId];
});


app.get('/', function (req, res) {
    var rid = uuid.v4();
    requests[rid] = res;
    webSocket.send(JSON.stringify({query:'data query', requestId: rid}));
});

var server = app.listen(3000, function () {
    var port = server.address().port
    console.log('Listening at %s', port)
});