Socket.io trigger events between two node.js apps?

2019-05-21 17:36发布

问题:

I have two servers, one for the back end app, and one that serves the front end. They are abstracted, but share the same database, I have a need for both to communicate real time events between each other using socket.io.

Front end

// serves a front end website
var appPort  = 9200; 

var express  = require('express');
var app      = express();
var http     = require('http');
var server   = http.createServer(app);
var io       = require('socket.io').listen(server);

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

    socket.on('createRoom', function(room) {
        socket.join(room); // use this to create a room for each socket (room) is from client side
    });

    socket.on('messageFromClient', function(data) {
        console.log(data)
        socket.broadcast.to(data.chatRoom).emit('messageFromServer', data);
    });


});

Back end

//Serves a back end app
var appPort  = 3100; 

var express  = require('express');
var app      = express();
var http     = require('http');
var server   = http.createServer(app);
var io       = require('socket.io').listen(server);

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

    socket.on('createRoom', function(room) {
        socket.join(room); // use this to create a room for each socket (room) is from client side
    });

    socket.on('messageFromClient', function(data) {
        console.log(data)
        socket.broadcast.to(data.chatRoom).emit('messageFromServer', data);
    });


});

As an admin I want to log in to my back end where I can see all the people logged in, there I can click on whom I would like to chat with.

Say they are logged in to the front end website, when the admin submits a message client side they trigger this socket.emit('messageFromClient', Message); how can I trigger messageFromClient on the front end using port 9200 submitting from the backend port 3100?

回答1:

You really dont need to start the socket.io server in the front end for this use case.

The way you can get it to work is :

  1. Keep the backend as it is, which acts as a Socket.IO server
  2. In the font end connect to the server using a Socket.IO client.

You can install the client by calling

npm install socket.io-client

and then connect to the server using :

var io = require('socket.io-client'),
socket = io.connect('localhost', {
    port: 3100
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('messageFromClient', { user: 'someuser1', msg: 'i am online' });

You can then create a map of socket objects with their corresponding username and send a message to that user based on your business logic.

More Information :

You may have to add cases like client disconnection etc. You can read more about the call backs for that here :

https://github.com/Automattic/socket.io-client