Skip to content Skip to sidebar Skip to footer

Sending Messages Client->server->client On Socket.io On Node.js

I'm using NodeJS+Socket.IO for simple web game. It works. Why? Here's my server.js var app = require('express').createServer(); var io = require('socket.io').listen(app); io.socke

Solution 1:

Client-side. A player moves and the function movePlayer is executed:

functionmovePlayer() {
    socket.emit ('player move', {map: 4, coords: '0.0'});
}

socket.on ('updatePlayer', function(msg) {
    console.log ('A player moves on map ' + msg.map + ' on coords ' + msg.coords);
});

Server-side. When someone moves, a 'updatePlayer' is emitted for each socket except the original player. On each client side, the updatePlayer is intercepted.

socket.on ('player move', function(msg) {
    io.sockets.emit ('updatePlayer', msg);
});

Solution 2:

Server side

socket.on('updatePlayer', function(updatePlayer){
  console.log("Someone just moved on the map!")
  updatePlayer() // will trigger the client side function
});

Client side

socket.emit('updatePlayer', function(){
  console.log('testing');
})

Post a Comment for "Sending Messages Client->server->client On Socket.io On Node.js"