0

I've been having some issues implementing a simple chat applicaion with node.js and socket.io using express.

This is my index.js file:

var express = require('express');
var http = require('http').Server(express);
var router = express.Router();
var io = require('socket.io')(http);

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/* Make the http server listen on port 3000. */
http.listen(3000, function(){
 console.log('listening on *:3000');
});

module.exports = router;

This does gives me this error:

listening on *:3000
Port 3000 is already in use

npm ERR! [email protected] start: `node ./bin/www`
npm ERR! Exit status 1
...

I have checked with "$ netstat -anp 2> /dev/null | grep :3000" and there seems to be nothing running on the port.

Secondly if I change the port number I get this in my console and I am unable to see that there is a socket connection or do anything with it:

listening on *:3010
GET /socket.io/?EIO=3&transport=polling&t=1422425200435-185 404 319.307 ms - 1136
GET /socket.io/?EIO=3&transport=polling&t=1422425205774-186 404 40.407 ms - 1136
GET /socket.io/?EIO=3&transport=polling&t=1422425210821-187 404 19.056 ms - 1136

Thanks.

1 Answer 1

1

I don't know if you are using express generator but I will assume you do.

To use the same port you have to create a new file (I named io.js)

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

io.on('connection', function (socket) {
  console.log("connected");
  socket.emit('news', { hello: 'world' });
});

module.exports = io;

And now in ./bin/www you have to add the following lines:

// After var app.
var io = require('../io');

...

// After server.on('listening', onListening); add:
io.attach(server);

With that everything will works fine.

:)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that. But I got this error io.attach(server); ^ TypeError: Object #<Object> has no method 'attach' at Object.<anonymous> (/home/hima/Documents/node/cc/bin/www:32:4)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.