当可以使用 socketIO 访问 nodeJS 服务器时,如何向用户显示?

How do I display to the user when the nodeJS server is reachable using socketIO?

我正在制作一个网络应用程序,当服务器可访问时向用户显示,以便他们可以 post 数据。目前它适用于我正在使用的代码,但是当另一个用户连接/断开连接时我遇到了一个问题,它直接影响另一个连接的客户端。

NodeJS 代码:

io.on('connection', function(socket) {
    console.log('Connected');
    io.emit('Connect');

    socket.on('disconnect', function () {
        console.log('Connection Lost');
        io.emit('disconnect');
    });
});

HTML代码:

     socket.on('disconnect', function(){
              $('#connection').html('disconnected');
              document.getElementById(id = 'save_button').style.display = "none"
              document.getElementById(id = 'not_save_button').style.display = "block"
          });

          socket.on('Connect',function() {
            $('#connection').html('connected');
            document.getElementById(id = 'save_button').style.display = "block"
            document.getElementById(id = 'not_save_button').style.display = "none"
          });

所以基本上我试图让每个页面只听服务器。它目前仅与一个客户端完美配合,但当您向系统添加任何其他内容时,它就无法运行。

我已经尝试过套接字 ID,但是当服务器重新连接时它们会更新,所以我找不到使它们起作用的方法。

相关套接字的Server.emit function emits the message to all clients. To send to a specific client, use the Socket.emit方法。在你的情况下:

io.on('connection', function(socket) {
  console.log('Connected');
  socket.emit('Connect');

  socket.on('disconnect', function () {
    console.log('Connection Lost');
});
io.on('connection', function(socket) {

    console.log('Connected');
    socket.emit('Connect');

});

io.on('disconnect', function () {
    console.log('Connection Lost');
    socket.emit('disconnect');
});

根据 Amit 的回答,我设法找到了解决方案。