nodejs socket.io cannot connect to server?

后端 未结 4 1833
别那么骄傲
别那么骄傲 2020-12-28 19:30

I\'ve been staring at node.js and socket.io examples all afternoon and i\'m trying to piece together a simple page that will tell me how many users I have connected to the s

4条回答
  •  星月不相逢
    2020-12-28 20:06

    I set up a test environment, installed express 3.0 and socket.io 0.9.5, and reproduced your error.

    Then I ran npm install express@2.5.1 made a couple backwards tweaks based on the migration guide, and it ran great.

    So I'm going to go ahead and suggest that socket.io is probably not compatible with express 3 yet, which still looks pretty unstable.

    My app.js tweaked for express 2:

    var express = require('express'),
        config = {
        port: 8080,
        hostname: 'localhost'
    };
    
    var server = module.exports = express.createServer();
    /* server configuration */
    server.set('views', __dirname + '/lib/views');
    server.set('view options', { layout: false });
    server.set('view engine', 'ejs');
    //server.register('.html', 'ejs');require('ejs').__express);
    server.use(express.cookieParser('keyboard unicorn'));
    server.use(express.bodyParser());
    server.use(express.methodOverride());
    server.use(express.session({ secret: 'keyboard unicorn' }));
    server.use('/', express.static(__dirname + '/lib/assets'));
    server.use(server.router);
    
    var io = require('socket.io').listen(server);
    
    io.set('log level', 2);
    
    var connections = { 'length': 0 };
    
    server.get('/', function( req, res ) {
            res.render('index', {
                    'page_title': 'sample application',
                        'number_of_connections': connections.length
                        });
        });
    
    io.sockets.on('connection', function(socket) {
            socket.__fd = socket.fd;
            connections[socket.__fd]=socket.remoteAddress;
            ++connections.length;
            console.log('user connected! There are a total of ' + connections.length + ' users online.');
            return socket.on('disconnect',function(){
                    delete conns[socket.__fd];
                    --connections.length;
                    console.log('user disconnected! There are a total of ' + connections.length + ' users remaining online.');
                });
        });
    
    server.listen(config.port);
    

    My index.ejs file:

    
    
    
       
       <%= page_title %>
    
    
    
    There is a total of <%= number_of_connections %> user(s) connected.

    I hope something here helps.

提交回复
热议问题