1
votes

I'm trying listen on a port for a TCP packet and then take the data from it and forward that to a UDP port. The reason is the software listening on the UDP port only accepts UDP but I want to use javascript websockets to send it data which only uses TCP.

2

2 Answers

1
votes

WebSockets is a lot more than just a simple TCP socket. The protocol is basically a HTTP Upgrade handshake (with some WebSockets-specific security handshaking sprinkled in).

If you just listen on a port and forward data blindly, it won't work since the browser won't actually be able to establish a WebSocket connection.

Have you considered using socket.io to handle the WebSocket end of things?

Then it's simple, just use dgram to send data over UDP:

io.sockets.on('connection', function (socket) {
  socket.on('sendudp', function (data) {
    var buf = new Buffer(data), udp = dgram.createSocket("udp4");

    udp.send(buf, 0, buf.length, 41234, "localhost", function(err, bytes) {
      udp.close();
    });
  });
});

Obviously replace 41234 and localhost with the desired destination port and host.

1
votes

There is no such thing as a 'TCP packet', and therefore no way of receiving one. TCP presents a byte-stream. Whether or not the datagrams that your UDP receiver is expecting will correspond with what you get by receiving on a TCP stream only you can tell, but you need to be aware that it is highly problematic.