2

我想重定向一个简单的 UDP 广播结果,其中包含来自不同设备的多个延迟(2 秒)消息,并将结果呈现为 http 响应。下面的代码运行良好,我可以通过 console.log 看到收集到的广播消息,但是 Web 响应是空的。如何正确实施?

var dgram = require("dgram");   
var http = require('http');

function broadcast(callback) {

    var data = '';

    var server = dgram.createSocket("udp4");

    server.on("message", function (message, rinfo) {
        data += message;    
    })

    server.bind(11000);

    var socket = dgram.createSocket("udp4");

    socket.bind();
    socket.setBroadcast(true);

    socket.send(Buffer([3]), 0, 1, 11001, '255.255.255.255', function(err, bytes) {     
        socket.close();
    });

    // dealy to collect all messages in 2 sec
    setTimeout(function () {
        callback(data);
    }, 2000);       
}

http.createServer(function (req, res) {

    res.writeHead(200, {'Content-Type': 'text/plain'});

    broadcast(function(data) {          
        res.write(data);
        console.log(data);          
    });

    res.end();

}).listen(6969, "0.0.0.0");

console.log('HTTP server running at http://0.0.0.0:6969/')
4

1 回答 1

2

res.end()在发送数据之前打电话。进入res.end()你的回调。

http.createServer(function (req, res) {

    res.writeHead(200, {'Content-Type': 'text/plain'});

    broadcast(function(data) {          
        res.write(data);
        console.log(data);          
        res.end();
    });

}).listen(6969, "0.0.0.0");
于 2012-05-09T19:36:03.000 回答