Using socket.io with express 4 generator

こ雲淡風輕ζ 提交于 2020-01-25 20:27:06

问题


New to node, so my apologies. I'm working on my app and I want to send the location using socket.io. I've found 1000 examples, but all refer to when express had no routes, and it all was at the app.js. All examples refer to chat applications. I was able to run an example piecing together several questions I searched but, I don't understand how to get the io that I finally got working on my app.js to interact with my index.js so I can use it with multiple emit parameters. express.io is outdated and I can't find anything current. On bin/www

/**
 * Socket.io
 */
var io = app.io
io.attach( server );

My app.js

var socket_io = require('socket.io');

var app = express();

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

So I can use:

io.on('connection', function (socket) {
    console.log('IO Ready');
});

I don't know how to use the sockets on my index.js (routes), I can't modularize it.

Thanks in advance.


回答1:


I have to say, I think the default generated project is bad for a socket.io setup. The node http.Server var is all the way in bin/www and not in app.js.

So the first thing is to move all the relevant stuff from bin/www to app.js. Mainly you just need

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

just like in the socket.io docs.

Now with io in app.js, we can use that when the routes are required. I forgot how exactly the default routes are set up, but I think they set up an app and just export it. Instead, you can set up something like

module.exports = function(app, io) {
    io.on('connection', function(socket) {
        console.log('connected!');
    }

    app.get('/foo', function() {
        ...
    }
}

And now when you require the routes, instead of having the default

var index = require('./routes/index');
app.use(index);

or something of that accord, you can just do

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

And that's how you get io into your routes. Or at least how I do it anyway.



来源:https://stackoverflow.com/questions/31016350/using-socket-io-with-express-4-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!