【问题标题】:Socket.io Client Not Receiving Data from Server CorrectlySocket.io 客户端未正确接收来自服务器的数据
【发布时间】:2013-03-13 10:32:42
【问题描述】:

server.js

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(process.env.PORT);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('message', { msg: 'world' });
  socket.on('message', function (msg) {
    console.log(msg);
    console.log('That was a message from the client :)');
  });
});

index.html:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('EDITED');
  document.write("test");
  socket.on('message', function (msg) {
    alert(msg);
    //console.log(data);
    socket.emit('message', { msg: 'hello there server' });
  });
</script>

服务器正在接受消息“hello there server”并在控制台中正确显示;但是,当服务器向客户端发送消息“hello”时,客户端应该给出一个弹出警报,该警报应该是“hello”。它不是弹出警告说“你好”,而是说:[object Object]

有什么想法吗?

【问题讨论】:

    标签: javascript html node.js networking socket.io


    【解决方案1】:

    响应是一个对象:

    socket.on('message', function(data) {
        alert(data.msg);
    

    我会考虑在发送这样的调试消息时使用console.log,因为您可以看到结构,而不仅仅是[object Object]

    【讨论】:

    • 感谢搅拌机!我会尽快接受你的回答。你喜欢……真正的搅拌机吗?
    • @nicktendo:真正的搅拌机?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 2016-06-16
    • 2019-08-08
    • 1970-01-01
    相关资源
    最近更新 更多