node.js 使用 socket.io 配置 Express 4.0 路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23281594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:13:06  来源:igfitidea点击:

Configuring Express 4.0 routes with socket.io

node.jsexpressroutessocket.io

提问by Ben

I have created a new Express application. It generated app.js for me and I have then created the following index.js bringing in socket.io:

我创建了一个新的 Express 应用程序。它为我生成了 app.js,然后我创建了以下 index.js 并引入了 socket.io:

var app = require('./app');
server=app.listen(3000);

var io = require('socket.io');
var socket = io.listen(server, { log: false });

socket.on('connection', function (client){
    console.log('socket connected!');
});

Can anyone advise how I would access socket.io within the routes files?

谁能建议我如何在路由文件中访问 socket.io?

For reference, the default generated app.js is below:

作为参考,默认生成的 app.js 如下:

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

回答by majidarif

SocketIO does not work with routes it works with sockets.

SocketIO 不适用于它适用于套接字的路由。

That said you might want to use express-ioinstead as this specially made for this or if you are building a realtime web app then try using sailsjswhich already has socketIO integrated to it.

这就是说,你可能想利用快递-IO,而不是为这个专门为此做,或者如果你正在建设一个实时web应用程序,然后使用尝试sailsjs已经有socketIO集成到它。

Do this to your main app.js

对您的主要 app.js

app = require('express.io')()
app.http().io()

app.listen(7076)

Then on your routes do something like:

然后在您的路线上执行以下操作:

app.get('/', function(req, res) {
    // Do normal req and res here
    // Forward to realtime route
    req.io.route('hello')
})

// This realtime route will handle the realtime request
app.io.route('hello', function(req) {
    req.io.broadcast('hello visitor');
})

See the express-io documentation here.

请参阅此处express-io 文档

Or you can do this if you really want to stick with express + socketio

或者,如果您真的想坚持使用 express + socketio,也可以这样做

On your app.js

在你的 app.js

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

Then create a file sockets.js

然后创建一个文件 sockets.js

module.exports = function(io) {

    io.sockets.on('connection', function (socket) {
        socket.on('captain', function(data) {
            console.log(data);
            socket.emit('Hello');
        });
    });
};

You can then call that to your routes/controllers.

然后您可以将其调用到您的路由/控制器。

回答by Armando Rueda

The route:

路线:

const Router = require('express').Router

const router = new Router();

router.get('/my-route', (req, res, next) => {
    console.log(req.app.locals.io) //io object
    const io = req.app.locals.io
    io.emit('my event', { my: 'data' }) //emit to everyone
    res.send("OK")
});

module.exports = router

The main file:

主文件:

const app = require('express')()
const server = require('http').Server(app);
const io = require('socket.io')(server)
const myroute = require("./route") //route file dir

app.use(myroute);

server.listen(3000, () => {
    console.log('?Usando el puerto 3000!');
});

app.locals.io = io