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

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

本文关键字:显示 用户 服务器 socketIO nodeJS 访问      更新时间:2023-09-26

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

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,但当服务器重新连接时,这些ID会更新,所以我找不到让它们工作的方法。

Server.emit函数向所有客户端发送消息。要发送到特定客户端,请使用相关套接字的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');
});

利用阿米特的回答,我设法找到了一个解决方案。