Connecting two clients to socket.io via node.js

I am trying to get two clients (players) to communicate with each other (exchanging, for example, strings) through socket.io. I have this code on clients (gameId is defined 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 routing, of course)

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

Basically I create a channel, and then, when users connect, they use the channel to exchange the message of the king "gameId", which only both of them can read (using the material on.(gameId+"" ... My problem is that when players connect (first, and then others), the first connected should warn the data received (because the second that connected, issued a message). Do any of you know why this does not happen?

Thanks.

+8
source share
1 answer

The socket.io server should act as the average person. It can receive messages from clients and send messages to clients. By default, it does not act as a β€œchannel” if you do not have server relay messages from clients to other clients.

There is a lot of good information about common goals on their website, http://socket.io and their repo, https://github.com/LearnBoost/socket.io

A simple chat client example might look 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" }); 

So far, the server can act as follows:

 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 }); }); }); 
+10
source share

All Articles