Create WebSockets between a TCP server and HTTP se

2019-03-13 17:10发布

I have created a TCP server using Node.js which listens to clients connections. I need to transmit data from TCP server to HTTP server again in Node.js possibly through a Websocket (socket.io).

However, I do not know how to create such connection such that TCP server is able to push data to HTTP server through Websocket.

Many Thanks.

3条回答
叛逆
2楼-- · 2019-03-13 17:51

If you need to communicate server-server than websockets is probably not a best choice. Try one of RPC libraries, or just use HTTP or your own protocol.

查看更多
再贱就再见
3楼-- · 2019-03-13 17:58

I was trying lot of things to get this work. Most of the time I was relying on socket.io to get this working, but it was just not working with TCP.

However, net.Socket suffices the purpose.

Here is the working example of it.

TCP Server

var net = require('net');

var HOST = 'localhost';
var PORT = 4040;

var server = net.createServer();
server.listen(PORT, HOST);

server.on('connection', function(sock) {
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.write("TCP sending message : 1");
    console.log('Server listening on ' + server.address().address +':'+ 
        server.address().port);
}).listen(PORT, HOST);

HTTP Server

var http = require('http').createServer(httpHandler),
    fs = require("fs"),
    wsock = require('socket.io').listen(http),
    tcpsock = require('net');

var http_port = 8888;

var tcp_HOST = 'localhost';
var tcp_PORT = 4040;

/**
 * http server
 */
function httpHandler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

http.listen(http_port);
console.info("HTTP server listening on " + http_port);

wsock.sockets.on('connection', function (socket) { 

    var tcpClient = new tcpsock.Socket();
    tcpClient.setEncoding("ascii");
    tcpClient.setKeepAlive(true);

    tcpClient.connect(tcp_PORT, tcp_HOST, function() {
        console.info('CONNECTED TO : ' + tcp_HOST + ':' + tcp_PORT);

        tcpClient.on('data', function(data) {
            console.log('DATA: ' + data);
            socket.emit("httpServer", data);
        });

        tcpClient.on('end', function(data) {
            console.log('END DATA : ' + data);
        });
    });

    socket.on('tcp-manager', function(message) {
        console.log('"tcp" : ' + message);
        return;
    });

    socket.emit("httpServer", "Initial Data");
});

Browser Client

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('httpServer', function (data) {
    console.log(data);
    document.write(data + "\r\n");
    socket.emit('tcp', "For TCP");
  });
</script>

This way, there is a socket opened between HTTP server and TCP server in Node.js.

查看更多
Viruses.
4楼-- · 2019-03-13 18:09

You can use either socket.io or ws (only WebSocket) on Node.js as client (not only in browser)

var io = require('socket.io-client');
var socket = io.connect('http://IP address of Websocket server');
socket.on('news', function (data) {
  console.log(data);
  socket.emit('my other event', { my: 'data' });
});
查看更多
登录 后发表回答