Communicate between a Rails app and a Node.js app

前端 未结 5 2145
长情又很酷
长情又很酷 2021-02-13 14:41

This question follows a previous one: Shall I use Node.js Instead of Rails for Real-time WebApps?

The question:

What\'s the best way of communic

5条回答
  •  日久生厌
    2021-02-13 15:05

    Why not open a TCP socket for communication between node & RoR ?

    var net = require('net');
    
    // create TCP server
    var server = net.createServer(function (socket) {
      // write down socket
      socket.write("Echo server\r\n");
      socket.pipe(socket);
    })
    
    // start server listening on port 8124
    server.listen(8124, "127.0.0.1");
    

    And in RoR you can connect to the socket

    require 'socket'      # Sockets are in standard library
    
    hostname = '127.0.0.1'
    port = 8124
    
    s = TCPSocket.open(hostname, port)
    
    while line = s.gets   # Read lines from the socket
      puts line.chop      # And print with platform line terminator
    end
    s.close               # Close the socket when done
    

    Then just write an abstraction on top of this TCP socket to synchronize your communication nicely and without requiring low level fiddling.

提交回复
热议问题