简体   繁体   中英

Forward data from UDP Socket to HTTP Server Node.js

I am looking to create a Web Service from data that is being retrieved via UDP connection and have decided to use Node.js and Socket.IO but, have come up short in that I think this combination does not give me the result I want. I was hoping someone could point me in the right direction.

Right now, I have the following:

// require http, socket and socket.io
var http     = require('http');
var dgram    = require('dgram');
var socketio = require('socket.io');

// setup HTTP server, Socket.IO and UDP Socket
var server = http.createServer( handleRequest ),
    io = socketio.listen(server),
    socket = dgram.createSocket("udp4");

// Every time I receive a UDP Message
socket.on("message", function(msg,rinfo) {
    // create a buffer we will store to
    var buffer = new Buffer(msg.length);

    // copy entire message into buffer
    msg.copy(buffer, 0, 0, msg.length);

    // if the message has length > 3
    if ( buffer.length > 3 ) {                
            .... take data off the socket ....

            // Create an XML document
            var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
            xml += ... ;
            xml += ... ;

            // emit a udp message event
            io.sockets.emit('udp message', xml);                
    }
});

function handleRequest(req, res) {
    res.writeHead(200, {'content-type': 'text/html'});
    res.end("<!doctype html> \
        <html><head> \
        <script src='/socket.io/socket.io.js'></script> \
        <script> \
            var socket = io.connect('localhost', {port: 8888}); \
            socket.on('udp message', function(message) { res.end(message) }); \
        </script></head></html>");
}

socket.bind(9876);
server.listen(8888);

Everything works well recv'ing the UDP data stream, creating the XML documents and I can see the XML being sent to the WebSocket but, I cannot retrieve the XML. Basically, I want a to continuously stream the XML once a user connects to the Web Service

Thoughts ? Dennis

This line looks suspiciously to me:

socket.on('udp message', function(message) { res.end(message) });

The client code is run in browser, you can't access res object. You can try to alert instead:

socket.on('udp message', function(message) { alert(message) });

In the real application, you will probably want to process the message and modify HTML of the page accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM