0

I am trying to send a simple message between two routes using Node.js, socket.io, and Express.

here are my express routes:

app.get('/', routes.index);
app.get('/controller', routes.controller);

and my socket.io on the server side:

io.sockets.on('connection', function (socket) {
    socket.emit('test', {});
      socket.on('clicked', function(data) {
      console.log('clicked received');
      socket.emit('do_stuff', data);
    });
});

in my index page:

<script>
var socket = io.connect('http://localhost:3001');
socket.on('test', function(data) {
  console.log('test received');
});
socket.on('do_stuff', function(data) {
  console.log('should do stuff here');
});
</script>

in my controller page:

  <button id='the_button'>Click Me</button>

  <script>
    var socket = io.connect('http://localhost:3001'); 
    socket.on('test', function(data) {
      console.log('test recieved');
    });
    $(function() {
      $("#the_button").click(function(e) {
        socket.emit("clicked", {});
    });
  </script>

I would like the 'do_stuff' to trigger some functionality on the index page when the button is clicked on the controller page. however, the socket.on('do_stuff',...) event is never fired. how can I fix this?

GSto
  • 41,512
  • 37
  • 133
  • 184

2 Answers2

0

You want to use socket.broadcast.emut instead of socket.emit

socket.emit only emits back to the socket that sent the message

See here for the differences: Whats the difference between io.sockets.emit and broadcast?

Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303
0

Make sure that socket is in the connected state before emitting event from event handler !!

Ashish
  • 8,441
  • 12
  • 55
  • 92