Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transfer UDP socket in node.js from Application to HTTP

Is it possible to transfer a Socket coming from a application to http via NodeJS?

I send my socket with a application (in c++) in UDP or TCP(if impossible in UDP...) to NodeJS.

My script from NodeJS:

var server = dgram.createSocket("udp4"); 
server.on("message", function (content, rinfo) 
{ 
   console.log("socket: " + content + " from " + rinfo.address + ":" + rinfo.port); }); 
   server.on("listening", function () { 
}); 
server.bind(7788);

Up to now does that function, but then how to transfer my socket to Socket.io for example?

I would like to send the socket to Socket.io (for example) for transfer the socket to HTTP. By using a function like this for example, but without renew a establishing a connection to socket.io :

io.sockets.on('connection', function (socket) { 
    socket.emit(content);
});

Thanks you for your help.

++ Metra.

like image 728
Metra Avatar asked Mar 03 '12 09:03

Metra


1 Answers

Here's a complete example with a socket.io server, a web server sending out a very simple page (it will just log all messages to console) and an UDP socket listening for messages, passing them to all connected clients:

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

var app = http.createServer(handleRequest),
    io = socketio.listen(app),
    socket = dgram.createSocket('udp4');

socket.on('message', function(content, rinfo) {
    console.log('got message', content, 'from', rinfo.address, rinfo.port);
    io.sockets.emit('udp message', content.toString());
});

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: 8000}); \
            socket.on('udp message', function(message) { console.log(message) }); \
        </script></head></html>");
}

socket.bind(7788);
app.listen(8000);

Update: As io.sockets.emit shows, all messages received on the UDP port 7788 are sent to all connected clients. If you want to route them based on some data in the message or similar, you could use Socket.IO's "room" feature: io.sockets.of(someRoom).emit. In the connection handler for Socket.IO, you can join each client to some room.

like image 150
Linus Thiel Avatar answered Sep 19 '22 14:09

Linus Thiel