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.
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:
While the server could act like this: