通过node.js连接两个带有socket.io的客户端

Mas*_*iar 9 node.js socket.io

我试图让两个客户端(玩家)通过socket.io相互联系(交换示例字符串).我在客户端上有这个代码(gameId在代码中定义):

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

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

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

基本上我创建的频道,然后当用户连接他们使用的频道,以交换之王"游戏ID",只有他们两个可以读取(使用的信息on.(gameId+"" ...的东西.我的问题是,当玩家连接(第一位的,然后是另一个),连接的第一个应该警告收到的数据(因为第二个连接发出的消息).你们有谁知道为什么没有发生这种情况?

谢谢.

btl*_*ler 13

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" });
Run Code Online (Sandbox Code Playgroud)

虽然服务器可以这样做:

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
            });
        });
     });
Run Code Online (Sandbox Code Playgroud)