Cesar Jr Rodriguez
Cesar Jr Rodriguez

Reputation: 1821

How to transmit socket.io emit events between different pages of a node application

I need send data from one page to another page using Socket.io in node. Both pages have different script. The pageA have the script fileA.js, and the pageB have the script fileB.js Here's my code:

fileA.js

$('canvas').on('mouseup', function() {
    var dataCan = JSON.stringify(canvas);
    socket.emit('upcanvas', dataCan);

});

and this the page that receives that data:

fileB.js

var socket = io.connect('http://localhost:3000');
socket.on('get-data', function(data){
    console.log(data);
});

And Here's the server file that receive that data and send the events of socket:

server.js

//Sockets
io.sockets.on('connection', function(socket)
  {
    socket.on('upcanvas', function(data){
    socket.emit('get-data', data);
  });
});

But that don't work!, I tried separately fileA.js and fileB.js and the socket works perfectly, but when I try to combine the emit/on events between that two pages, don't occurs nothing. What's wrong in that code?

Upvotes: 0

Views: 1828

Answers (1)

Cesar Jr Rodriguez
Cesar Jr Rodriguez

Reputation: 1821

I've found the solution !, simply this:

//Sockets
io.sockets.on('connection', function(socket)
 {
socket.on('upcanvas', function(data){
socket.broadcast.emit('get-data', data);
});
 });

Upvotes: 1

Related Questions