Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connecting two clients with socket.io through node.js

I'm trying to make two clients (players) contact each other (exchanging for example strings) through socket.io. I have this code on the clients (gameId is defined back in the code):

var chat = io.connect('http://localhost/play');
chat.emit(gameId+"", {
    guess: "ciao"
});
chat.on(gameId+"", function (data) {
    alert(data.guess);
});

While on the server I have this (which is one of the first things I do, not in routing of course)

var messageExchange = io
    .of('/play')
    .on('connection', function (socket) {
        socket.emit('message', {
            test: 'mex'
        });
      });

Basically I create the channel, then when users connect they use the channel to exchange a message of the king "gameId" that only the both of them can read (using the on.(gameId+"" ... stuff. My problem is that when players connect (first one, then the other), the first one that connected should alert the data received (because the second one that connected emitted a message). Does anyone of you know why this is not happening?

Thanks.

like image 259
Masiar Avatar asked Oct 19 '11 14:10

Masiar


1 Answers

The socket.io server should act like a middle man. It can receive messages from clients and send messages to clients. It doesn't act as a "channel" by default, unless you have the server relay messages from clients to other clients.

There's a lot of good info on common uses on their website, http://socket.io and their repo, https://github.com/LearnBoost/socket.io

A simple example of a chat client could be something like this:

var chat = io.connect("/play");
var channel = "ciao";

// When we connect to the server, join channel "ciao"
chat.on("connect", function () {
    chat.emit("joinChannel", {
        channel: channel
    });
});

// When we receive a message from the server, alert it
// But only if they're in our channel
chat.on("message", function (data) {
    if (data.channel == channel) {
        alert(data.message);
    }
});

// Send a message!
chat.emit("message", { message: "hola" });

While the server could act like this:

var messageExchange = io
    .of('/play')
    .on('connection', function (socket) {
        // Set the initial channel for the socket
        // Just like you set the property of any
        // other object in javascript
        socket.channel = "";

        // When the client joins a channel, save it to the socket
        socket.on("joinChannel", function (data) {
            socket.channel = data.channel;
        });

        // When the client sends a message...
        socket.on("message", function (data) {
            // ...emit a "message" event to every other socket
            socket.broadcast.emit("message", {
                channel: socket.channel,
                message: data.message
            });
        });
     });
like image 73
btleffler Avatar answered Oct 11 '22 09:10

btleffler