简体   繁体   中英

Socket.io and Express 4

I am building a simple web app with node.js, express 4 and socket.io (latest version).

My problem is that the proposed syntax for socket.io (from their website) does not correspond with what I have from express.

This is the socket.io way to include everything and get started:

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

Problem though is that I have auto generated a project with express-generator and the beginning of my code looks like this:

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

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

var app = express();

Also, this is my 'bin/www' file:

#!/usr/bin/env node
var debug = require('debug')('ase');
var app = require('../app');

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});

I do not seem to find any reference to the 'http' package and running socket.io seems to depend on it.

What is the proper way to include and work with socket.io in an express 4 project?

As a side question, how should I structure my code? That is, should I include all my socket.io logic inside the app.js (I think not) or should I make another file and link it?

Any ideas?

For your first two questions, I believe this post will help you with that Using socket.io in Express 4 and express-generator's /bin/www

As for your last question, you should put the relevant socket.io logic within the file of where it's needed. It definitely should not all be stored in one place. In the chat example of socket.io , you'll notice that they separate the socket.io logic from when you send a message to when you receive one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM