node.js侦听UDP并转发到连接的http Web客户端

时间:2013-04-24 10:49:49

标签: node.js websocket socket.io

我是node.js的新手,如果这很简单,请原谅无知。

我想要做的是设置一个简单的node.js http服务器,网络客户端连接到该服务器。我还希望node.js服务器在单独的端口上充当UDP侦听器,在该端口上它将从其他应用程序接收JSON有效负载。我希望node.js服务器立即将这些JSON有效负载转发到一个或多个连接的Web客户端。

我远离一些最初的谷歌搜索:

  1. 创建一个简单的node.js http服务器,该服务器使用静态html页面进行响应:

    //Initialize the HTTP server on port 8080, serve the index.html page
    var server = http.createServer(function(req, res) {
        res.writeHead(200, { 
            'Content-type': 'text/html'});
            res.end(fs.readFileSync(__dirname + '/index.html'));
        }).listen(8080, function() {
            console.log('Listening at: 127.0.0.1 8080');
        }
    );
    
  2. 在单独的端口上初始化UDP服务器:

    //Initialize a UDP server to listen for json payloads on port 3333
    var srv = dgram.createSocket("udp4");
    srv.on("message", function (msg, rinfo) {
      console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
      io.sockets.broadcast.emit('message', 'test');
      //stream.write(msg);
      //socket.broadcast.emit('message',msg);
    });
    
    srv.on("listening", function () {
      var address = srv.address();
      console.log("server listening " + address.address + ":" + address.port);
    });
    
    srv.bind(5555);
    
  3. 使用socket.io在Web客户端和服务器之间建立实时连接:

    //this listens for socket messages from the client and broadcasts to all other clients
    var io = require('socket.io').listen(server);
    io.sockets.on('connection', function (socket) {
        socket.on('message', function (msg) {
          console.log('Message Received: ', msg.data.skeletons[0] ? msg.data.skeletons[0].skeleton_id : '');
          socket.broadcast.emit('message', msg);
        }
      );
    });
    
  4. 我想我的问题是我不知道如何桥接2和3,以便将收到的UDP数据包广播到已连接的socket.io客户端。或者也许有一种更简单,更优雅的方式呢?我发现socket.io的文档缺乏......

    编辑:感谢修复代码格式的人

1 个答案:

答案 0 :(得分:11)

我为你做了一个运行的例子:http://runnable.com/UXsar5hEezgaAACJ

目前它只是一个环回客户端 - > socket.io - > udp客户端 - > udp服务器 - > socket.io - >客户端。

这是它的核心:

var http = require('http');
var fs = require('fs');
var html = fs.readFileSync(__dirname + '/index.html');

//Initialize the HTTP server on port 8080, serve the index.html page
var server = http.createServer(function(req, res) {
  res.writeHead(200, { 
    'Content-type': 'text/html'
  });
  res.end(html);
}).listen( process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP, function() {
  console.log('Listening');
});

var io = require('socket.io').listen(server);

io.set('log level', 0);

io.sockets.on('connection', function (socket) {
  socket.emit('message', 'connected');
  socket.on('message', function (data) {
    console.log(data);
    var address = srv.address();
    var client = dgram.createSocket("udp4");
    var message = new Buffer(data);
    client.send(message, 0, message.length, address.port, address.address, function(err, bytes) {
      client.close();
    });
  });
});

var dgram = require('dgram');

//Initialize a UDP server to listen for json payloads on port 3333
var srv = dgram.createSocket("udp4");
srv.on("message", function (msg, rinfo) {
  console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
  io.sockets.emit('message', 'udp');
});

srv.on("listening", function () {
  var address = srv.address();
  console.log("server listening " + address.address + ":" + address.port);
});

srv.on('error', function (err) {
  console.error(err);
  process.exit(0);
});

srv.bind();