1

I've been digging for hours for an easy solution to this question and I can't find one. How can I get started with Socket.io after using Express's application generator. For example, if I create a new app with express myapp and npm install --save socket.io how do I use in in my index.jade file?

My index.jade file is plain HTML right now and looks as such

html.
<head>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();

      socket.on('message', function(msg){
          console.log('you got a message');
        });
    </script>
</head>
<body>
    <canvas id="mycanvas" width="768" height="720"></canvas>
</body>

My routes/index.js file looks as such

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

router.get('/', function(req, res, next) {
    io.emit('text', { for: 'everyone' });  
    res.render('index', { title: 'Express' });
});

module.exports = router;

Nothing happens when I go to my app's homepage though. I followed this SO answer but my app only fires the "A user connected" message. My io.emit never fires in my index.js file.

Community
  • 1
  • 1
Brodan
  • 152
  • 1
  • 18
  • put `io.emit` inside `io.on( "connection")` callback – hassansin Aug 03 '15 at 23:56
  • I don't want all of my socket.io logic inside my ```app.js``` file though, I need to be able to use ```emit``` from inside of my ```router.get``` function. – Brodan Aug 04 '15 at 00:00
  • well, you have to make a socket connection first before emitting. Your code emits first and then when render completes in browser it makes the connection. – hassansin Aug 04 '15 at 00:13
  • Have you started your server? and attached the webSocket infrastructure to your server? – jfriend00 Aug 04 '15 at 07:11

1 Answers1

1

Write the socket code outside the REST api and try this:

io.on( "connection", function( socket )
{
    console.log( "A user connected" );
    socket.emit('text', { for: 'everyone' });
});
Subham
  • 1,414
  • 4
  • 17
  • 34