N
N
neodekvat092015-09-26 12:11:41
JavaScript
neodekvat09, 2015-09-26 12:11:41

How to integrate socket.io in express-generator?

Hello, I recently wrote a chat on socket.io and a local express'a 4 server. There is not much code, so far it is only in two files (client.js, server.js), I want to try to put it into full-fledged production (for practice), but this requires routes, etc. And that means a full-fledged express, used express-generator, and ... I just can’t connect socket.io. Googled, but not all answers help, and, in most cases, they are individual.
As I understand it, the whole problem is in the directory, or rather the /bin/www. Through it, you need to connect socket.io ... So far, everything rests on this.
Who has experience, tell me, only this problem separates from production :'(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aves, 2015-09-26
@neodekvat09

Yes, you can think of many different ways, for example, add to app.js

app.io = function(server) {
    var io = require('socket.io')(server);
    io.on('connection', function (socket) {
        //...
    });
}

And in bin/www app.io(server);
Or separate the handler into a separate module
// routes/socket.js
function handler(socket) {
    // ...
}

module.exports = handler;

// app.js
var io = require('socket.io');
var socket = require('./routes/socket');

app.io = function(server) {
    io(server).on('connection', socket);
};

// bin/www
app.io(server);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question