DeepSpace
DeepSpace

Reputation: 81684

Socket.io and express.js, how to make it work?

I've seen many variations online but nothing seems to be working for me. How to get socket.io 1.3.5 and express 4.12.2 to work?

This is what I have right now. The error I get is 404 because the server can't serve /socket.io/socket.io.js.

app.js:

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

io.on('connection', function (socket) {
   console.log('connected');
});

index.hjs:

<script src="/socket.io/socket.io.js"></script>
        <script>
          var socket = io.connect();
          socket.on('news', function (data) {
            console.log(data);
          });
</script>

NOTE: I've also tried to use the cdn <script src="https://cdn.socket.io/socket.io-1.3.5.js"></script> but with no success.

Upvotes: 2

Views: 490

Answers (1)

Dineshaws
Dineshaws

Reputation: 2083

To use socket.io with express we have required some changes in default confiscation of expesss.

app.js:

var app = require('express')();

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

module.exports = app;

io.js

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

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

module.exports = io;

bin/www:

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

io.attach(server);
server.listen(8080);

Now for index template you should use like following

<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
      var socket = io();
      socket.on('news', function (data) {
        console.log(data);
      });

      });
});
</script>

Its a working code..

Thanks

Upvotes: 4

Related Questions