Configuring 'simplest' node.js + socket.IO + Express server

北战南征 提交于 2020-01-06 06:47:25

问题


Realized after setting up a simple node.js socket.IO server that it isn't sufficient to handle even the simplest webpages containing script tags.

So I investigating express which is a simple web framework for node.js.

After looking thru the express documentation http://expressjs.com/guide.html I was still confused as to how I simply combine express with socket.IO on a node.js server.

Couple hours of googling later I came across this tutorial https://www.digitalocean.com/community/articles/how-to-install-express-a-node-js-framework-and-set-up-socket-io-on-a-vps

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , http = require('http');

var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server); // this tells socket.io to use our express server

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.static(__dirname + '/public'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);


console.log("Express server listening on port 3000");
io.sockets.on('connection', function (socket) {
    console.log('A new user connected!');
    socket.emit('info', { msg: 'The world is round, there is no up or down.' });
});

My question is, would anyone reading this configure their server differently? I don't need anything special, no session handling etc, just the ability to serve html pages containing links to external CSS and javascript files.


回答1:


  1. Remove the first app.configure wrapper but leave it's contents. It is useless in general, but especially if you don't pass an argument to it.
  2. Remove methodOverride and bodyParser as you aren't using them



回答2:


Thanks for all the replies. Finally have something that works and am posting so someone else may benefit. My first attempt(above) was obviously NOT the simplest solution:)

//npm install express
//npm install socket.io
var express = require('express');
var server = express.createServer();

server
    .use( server.router )
    .use( express.static(__dirname+'/public') )
    .get('/api', function(req, res) {
        res.write('API');
    });

server=server.listen(3000);

var io = require('socket.io');
var socket = io.listen(server);

socket.on('connection', function (client){
  // new client is here!


});


来源:https://stackoverflow.com/questions/20428162/configuring-simplest-node-js-socket-io-express-server

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