0

使用 socket.io 客户端在发布表单时挂起(页面不断加载) - 停止客户端服务器立即再次运行良好。

服务器

app.post('/', function(req, res) {
  io.sockets.emit('messages', { 
    user: req.body.user,
    message: req.body.message
  });
});

客户

<script src="socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('messages', function (data) {
    console.log(data);
    $('.entry').first().before(
        '<div class="entry well well-large">'
        + data.user
        + ' says: '
        + data.message
        + '</div>');
});
4

1 回答 1

4

您应该始终结束 HTTP 请求,但您没有在post处理程序中这样做。如果您不这样做,Express 不会向您的浏览器返回答案,并且您的浏览器将继续等待(直到某个时候它厌倦了等待并产生超时)。

试试这个:

app.post('/', function(req, res) {
  io.sockets.emit('messages', { 
    user: req.body.user,
    message: req.body.message
  });
  // end the request by ending the response
  res.end();
});

(用 发送消息是不够的socket.io,因为那是一个单独的协议)

于 2013-05-19T20:08:42.863 回答