Create WebSockets between a TCP server and HTTP server in node.js

后端 未结 3 1150
一个人的身影
一个人的身影 2021-02-03 14:20

I have created a TCP server using Node.js which listens to clients connections. I need to transmit data from TCP server

3条回答
  •  面向向阳花
    2021-02-03 14:48

    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

    
    
    

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

提交回复
热议问题