Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Express 4 with Socket.io #2145

Closed
programming-kid opened this issue May 27, 2014 · 8 comments
Closed

Express 4 with Socket.io #2145

programming-kid opened this issue May 27, 2014 · 8 comments

Comments

@programming-kid
Copy link

I am new to Express 4 & socket.io i can't get a working example of express4 with socket.io ,all examples are about express 3 and socket.io

here is my app.js

var express = require('express');
var io = require('socket.io');
var path = require('path');
var swig = require('swig');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

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

var app = express(),
    server = require('http').createServer(app),
    sio = io.listen(server);

// view engine setup

app.engine('html', swig.renderFile);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

sio.sockets.on('connection', function(socket) {
    socket.emit('news', {
        hello: 'world'
    });
    socket.on('my other event', function(data) {
        console.log(data);
    });
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

here is my client code

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Express</title>
</head>
<body>
<h3>Hello Express</h3>

    <script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost:3000');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>
</body>
</html>

i can't get it working
/socket.io\socket.io.js return 404 on client side

Can anyone please help me get setup with socket.io with Express4.2

thanks

@gs-akhan
Copy link

Hi,
Firstly you are not listening on any port for your server.. so the url localhost:3000/socket/socket.io.js onclient throws 404. so the fix goes this way
var app = express(),
server = require('http').createServer(app).listen(3000),
sio = io.listen(server);

Hope that helps.. :)

@programming-kid
Copy link
Author

No this dosen't work infact it breaks the entire code , express works fine but not socket.io

@gs-akhan
Copy link

what do u mean by breaks all code ? whats the error u get ?

@programming-kid
Copy link
Author

i find express 4 different from express 3

i get following error

Error: listen EADDRINUSE
    at errnoException (net.js:904:11)
    at Server._listen2 (net.js:1042:14)
    at listen (net.js:1064:10)
    at Server.listen (net.js:1138:5)

@gs-akhan
Copy link

aaaah.. !! this is a different issue.. this means 3000 port is already used by some other process
change it to 8080 or something else and try..

@programming-kid
Copy link
Author

@gs-akhan thanks , you were right infact everything was in place only problem was i created express app using express genrator which create a dir

./bin/www

which has following code

#!/usr/bin/env node
var debug = require('debug')('demo.app');
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);
});

which caused above error

adding following lines to end of app.js

var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

Solves it

thanks @gs-akhan

@dougwilson
Copy link
Contributor

Hi guys, thanks for getting this figured out. In the future, though, this is a type of question that would be better sited for something like stackoverflow.com :)

@netpoetica
Copy link

FWIW, I was able to solve this by removing boilerplate error handler middleware. Have opened an issue with express-generator. @programming-kid the solution you mentioned did not solve the issue for me

@expressjs expressjs locked and limited conversation to collaborators Jul 6, 2014
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants