Socket.io broadcast.emit在这里使用不正确?

时间:2012-11-27 11:49:28

标签: node.js events socket.io broadcast

我正在练习的这个聊天应用程序(对Node和Socket.IO来说是新手)表现不错,除了我无法让服务器向所有客户端广播消息。我检查了不一致的变量(并且可能在玩游戏时创建了一些,我的道歉; P)但它不起作用?我很困惑,因为我没有收到任何控制台错误或类似的东西,这使得调试难以置信。可能是因为我第一次遇到回调如何最终以不受欢迎的方式嵌套?

无论如何,这里有一些代码:

App.js:

// Require dependencies
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);

// Listen for connections
io.sockets.on('connection', function(client) {

  console.log("Someone is connecting...");

  client.on('join', function(name) {
    client.set('nickname', name);
    console.log(name+" has connected!");
    client.broadcast.emit('connected', name + " has connected");
  });

  // Receive messages from the client and broadcast them to everyone
  client.on('messages', function(data) {

    client.get('nickname', function(err, name) {
      client.broadcast.emit("chat", name + ": " + data);
    });

  });
});

// Without this line, the CSS will not work
app.use('/public', express.static(__dirname + '/public'));

// Route index.html to the root path
app.get('/', function(request, response) {
    response.sendfile(__dirname + "/index.html");
});

// Listen for GET requests to the server
server.listen(3000);
console.log("Listening on port 3000");

的index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Chatapp</title>
        <link rel="stylesheet" type="text/css" href="public/default.css"></link>
    </head>
    <body>
        <h1 class="title">Chatapp</h1>

        <div id="wrapper">
            <div id="online">

            </div>

            <div id="body">
                <div id="status"></div>
                <div id="chat">

                </div>
            </div>

            <div id="input">
                <form id="chatform">
                    <input type="text" id="message"></input>
                    <input type="submit" id="send" value="Send!"></input>
                </form>
            </div>
            <div class="clear"></div>
        </div>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="/socket.io/socket.io.js"></script>
        <script>
            // Wait until DOM is ready
            $(document).ready(function() {

                // Establish a connection to the server
                var server = io.connect('http://localhost:3000');

                // On submit, send the chat form message to the server, prevent default redirect and reset the chat form
                $('#chatform').submit(function(e) {
                    e.preventDefault();
                    var message = $('#message').val();
                    server.emit('messages', message);
                    $('#chatform')[0].reset();
                });

                server.on('connect', function(data) {
                    nickname = prompt('What is your nickname?');
                    $('#status').html('Connected to Chatapp as ' +nickname);
                    server.emit('join', nickname);
                });

                server.on('connected', function(data) {
                    $('<p>'+data+'</p>').appendTo('#chat');
                });

                // Listen for messages broadcasted to every client by the server - this does not work for some reason.
                server.on('chat', function(data) {
                    $(data).appendTo('#chat');
                });
            });
        </script>
    </body>
</html>

/public/default.css:

body {
  margin:  0;
  padding:  0;
  font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}

a {
  color: #00B7FF;
}

#wrapper {
    margin: 0 auto;
    width:  940px;
    height: 500px;
    padding: 0;
    border: 1px solid #000;
}

#online {
    float: left;
    width: 188px;
    height: 480px;
    padding: 10px;
    border-right: 1px solid #000;
    background: #3d3d3d;
    color: #eee;
    box-shadow: inset 1px 1px 0px #fff, inset -1px -1px 0px #fff;
}

#body {
    float: left;
    width: 731px;
    height: 439px;
    padding: 0;
    border-bottom: 1px solid #000;
}

#status {
    color: #eee;
    height: 30px;
    border-bottom: 1px solid #000;
    background: #3d3d3d;
    padding-left: 10px;
    line-height: 30px;
    box-shadow: inset 1px 1px 0px #fff, inset -1px -1px 0px #fff;
}

#chat {
    background: #c4f2eb;
    height: 388px;
    padding: 10px;
    box-shadow: inset 1px 1px 0px #fff, inset -1px -1px 0px #fff;
}

#input {
    float: left;
    height: 60px;
    width: 731px;
}

.clear {
    clear: both;
}

h1.title {
    text-align: center;
}

input#message {
    float: left;
    margin: 0;
    width: 640px;
    height: 58px;
    border: none;
    font-size: 28px;
    padding-left: 10px;
    box-shadow: inset 1px 1px 3px rgba(0,0,0,0.3);
}

input#message:focus {
    border: none;
    outline: none;
    box-shadow: inset 1px 1px 3px #55ba57, inset -1px -1px 3px #55ba57;
}

input#send {
    float: left;
    background: #55ba57;
    color: #fff;
    border: none;
    height: 60px;
    margin: 0;
    width: 81px;
    border-left: 1px solid #000;
    box-shadow: inset 1px 1px 0px #fff, inset -1px -1px 0px #fff;
}

input#send:hover {
    background: #489949;
    cursor: pointer;
}

input#send:active {
    background: #1e7520;
}

1 个答案:

答案 0 :(得分:4)

好的,让我们把这个问题分解成许多小问题;)

  1. 当您说您无法登录(或提醒)data时,您在尝试此时间? (你的评论有问题)

    如果这是server.on('connect', function(data) {...,您将永远无法获得任何数据。 connect事件纯属信息性。

  2. 这两个都不会将数据发送回connected\chat的客户端。

    client.broadcast.emit('connected', name + " has connected");
    client.broadcast.emit("chat", name + ": " + data);
    

    因此,如果您希望它们打印在同一个客户端窗口中,您还必须直接在其下面client.emit,将消息发送到导致操作的客户端窗口。

    编辑:这是来自文档:广播意味着向除了启动它的套接字之外的所有人发送消息。

  3. 您的服务器广播chat个事件,但您的客户端仅监听messages个事件。 (FIXED)

  4. 如果您有任何其他问题,请与我们联系。

    • 我不会在客户端和服务器上的“客户端”上调用您创建的“服务器”套接字。让一切变得有些混乱。 ;)