Transfer UDP socket in node.js from Application to

2019-03-16 21:50发布

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.

1条回答
Summer. ? 凉城
2楼-- · 2019-03-16 22:24

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.

查看更多
登录 后发表回答