Calling socket.io from rest api in node

2020-07-17 14:58发布

问题:

I am trying to emit a socket.io event from my restful api.

My current setup looks something like this:

app.js setups an express app and creates all the necessary routes like:

var app = express();
...
var routesApi = require('./app_api/routes/index');
app.use('/api', routesApi);
module.exports = app;

server.js creates a server and hooks up both express app and socket.io

var http = require('http');
var server = http.createServer(app);

require('../app_server/controllers/socket.js').socketServer(server);

Everything works and I can successfully fire a socket event from the client, process it inside socket.js and emit the results.

However, what I am trying to do is call socket.js method from my restful api and I can't figure out how to hook that up.

Since socket server is initialized inside server.js and my api routing is hooked up in app.js, I am not sure what's the proper way of getting them to talk to each other.

Thank you

回答1:

You should initialise Socket.io inside the express section (or where you have app) so you can save it inside the express request and use it in every route you want.

So in your app.js you create the socket and then you save it in app:

var socketIo =  require('../app_server/controllers/socket.js').socketServer(server); // Make sure this returns the socketio

app.set('socketIo', socketIo);

Now in every route you can do this:

app.route('/test').get(function (req, res) {
   var socket = req.app.get('socketIo');
   socket.emit('hello', 'world');
   res.end();
}