如何使用Node.js从客户端正确地向服务器发送数据?

时间:2017-07-25 01:32:57

标签: javascript node.js server client emit

当客户端连接到服务器时,应该向控制台发送一条消息。我没有收到任何错误,所以我很困惑我的问题实际上是什么。

服务器:正如您所看到的,客户端已连接。 enter image description here
客户端:该消息未显示在控制台中。 client image
(原谅我的链接,我没有10个声誉)

如何将信息打印到控制台?

我已经阅读了其他类似的帖子,但它们没有帮助:(

2 个答案:

答案 0 :(得分:0)

执行io.connect()时,该调用是异步的,而不是立即的。在客户端生成connect事件之前,您无法立即向服务器发出:

 var socket = io.connect()
 socket.on('connect', function() {
     // it is safe to call `.emit()` here
     socket.emit("sndMsg", someData);
 });

答案 1 :(得分:0)

<强>的index.html

<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io();

            socket.on('welcome', function(data) {
                addMessage(data.message);

                // Respond with a message including this clients' id sent from the server
                socket.emit('i am client', {data: 'foo!', id: data.id});
            });
            socket.on('time', function(data) {
                addMessage(data.time);
            });
            socket.on('error', console.error.bind(console));
            socket.on('message', console.log.bind(console));

            function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
            }
        </script>
    </head>
    <body>
        <ul id='messages'></ul>
    </body>
</html>

<强> server.js

var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function(socket) {
    // Use socket to communicate with this particular client only, sending it it's own id
    socket.emit('welcome', { message: 'Welcome!', id: socket.id });

    socket.on('i am client', console.log);
});

app.listen(3000);