Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.sockets.on('connection', function (socket) {
socket.on('set nickname' , function (nickname) {
socket.nickname = nickname;
console.log(nickname + ' just connected!');

});

socket.on('msg' , function (msg) {
socket.msg = msg;
io.sockets.emit('response', msg);
});

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

});

app.listen(8080);

The reason I know it works is because, when I load the page and this script executes:

// SERVER STUFF
socket.on('connect', function () {
    console.log('We are connected!');
    name = $(".name").val();
    this.emit('set nickname', name, function (success) {});
    msg = name + "|" + currX + "|" + currY + "|" + currentMap;
    this.emit('msg', msg, function (success) {});

    socket.on('response', function (data) {
        var theMsg = data.split("|");
        sayDialog("New player! " + theMsg[0] + " connected on map " + theMsg[3] + " on coordinates (" + theMsg[1] + "," + theMsg[2] + ")");
    });
});

I get in my dialogbox ("CSS div") something like New player! weka connected on map 4 on coordinates (10,5)

OK, cool, so it works! However, when I "move" I try sending a message to server using this

  socket.on('updatePlayer', function () {
    console.log("Testing...");
  }); 

I don't even see console say Testing. I don't know why.

like image 568
test Avatar asked May 15 '12 12:05

test


2 Answers

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');
})
like image 22
Tronix117 Avatar answered Sep 28 '22 06:09

Tronix117


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

function movePlayer () {
    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);
});
like image 174
Wilk Avatar answered Sep 28 '22 06:09

Wilk