Express - 如何在路由文件中使用io.socket.emit?

时间:2015-05-20 11:50:50

标签: javascript node.js express socket.io

我有一个带快递的应用程序(nodeJS)。

想在DB上写一些数据时发出io.socket,所以需要在路由文件中发出(例如/routes/save.js)

这是我的app.js

var express = require('express');
var save = require('./routes/save');
var http = require('http');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
......
io.on('connection', function(socket){
    socket.on('newTweet', function(msg){
        io.emit('newTweet', msg);
    });
});

app.use('/save', save);
.....
module.exports = app;
server.listen(3000, function () {
    var host = server.address().address
    var port = server.address().port
})

你能帮我在io.socket.emit('event')写一下/routes/save.js吗?

3 个答案:

答案 0 :(得分:4)

我发现了一种方法。

app.use('/save', save);需要在app.js

中编写以下代码之前
app.use(function(req, res, next) {
    req.io = io;
    next();
});

并在此之后从save.js中的io参数获取req 例如

var express = require('express');
var router = express.Router();

router.post('/', function(req, res, next) {
    .....
    var io = req.io;
    io.emit('newTweet', 'test');
    .....
});

module.exports = router;

如果你知道比这个更好的方式,请告诉我。

答案 1 :(得分:0)

您可以将io对象传递给您的路线,如下所示:

var app = express();
var io           = socket_io();
app.io           = io;

require('./routes/index')(app,io);

答案 2 :(得分:0)

import {createServer} from 'http';
import express from 'express';
import socketio  from 'socket.io';

const server = createServer(app);
const io = socketio.listen(server);

app.use(function (req, res, next) {
    req.io = io;
    next();
})
app.get('/', function (req, res) {
   const ioConnection = req.io;
   ioConnection.emit('nouveau_client', body.pseudo);
});
io.sockets.on('connection', function (socket) {
    socket.on('nouveau_client', function (user) {
       socket.broadcast.emit('nouveau_client', user.pseudo);
   });
});
server.listen(3000);