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

后端 未结 3 1135
一个人的身影
一个人的身影 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:39

    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' });
    });
    
    0 讨论(0)
  • 2021-02-03 14:44

    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.

    0 讨论(0)
  • 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

    <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.

    0 讨论(0)
提交回复
热议问题