通过node.js连接两个客户端与socket.io

我试图让两个客户(玩家)通过socket.io互相联系(交换string)。 我在客户端上有这个代码(gameId是在代码中定义的):

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

虽然在服务器上,我有这个(这是我做的第一件事,当然不是路由)

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

基本上我创build了频道,然后当用户连接时,他们使用频道交换国王“gameId”的消息,只有他们两个人都可以阅读(使用on.(gameId+"" ... stuff。我的问题是当玩家连接(第一个,然后是另一个)时,第一个连接的应该提醒收到的数据(因为第二个连接发出了一条消息)。你们有谁知道为什么这不会发生?

谢谢。

socket.io服务器应该像一个中间人一样。 它可以接收来自客户端的消息并将消息发送给客户端。 它不会默认作为“通道”,除非您将服务器中继消息从客户端传递到其他客户端。

在他们的网站上有很多常用的信息, http://socket.io和他们的回购, https://github.com/LearnBoost/socket.io

一个聊天客户端的简单例子可能是这样的:

 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" }); 

虽然服务器可以这样做:

 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 }); }); });