简体   繁体   English

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

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

I am making a web app that shows the user when the server is reachable so they can post data. 我正在制作一个Web应用程序,向用户显示服务器何时可以访问,以便他们可以发布数据。 Currently it works with the code I am using but I am having an issue when another user connects / disconnects it directly affects another client that is connected. 当前,它可以与我使用的代码一起使用,但是当另一个用户连接/断开连接时,它直接影响另一个连接的客户端时,我遇到了问题。

NodeJS code: NodeJS代码:

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

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

HTML code: 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"
          });

So basically I am trying to make each page only listen to the server. 因此,基本上,我试图使每个页面仅侦听服务器。 It currently works perfectly with just one client but when you add anything else to the system it can't function. 目前,它仅可与一个客户端完美配合,但是当您向系统中添加其他任何功能时,它将无法正常运行。

I have tried socket ID but these get updated when the server reconnects so I couldn't find a way to make these work. 我已经尝试过套接字ID,但是当服务器重新连接时这些ID会更新,所以我找不到使它们起作用的方法。

The Server.emit function emits the message to all clients. Server.emit函数将消息发送给所有客户端。 To send to a specific client, use the Socket.emit method of the relevant socket. 要发送到特定的客户端,请使用相关套接字的Socket.emit方法。 In your case: 在您的情况下:

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');
});

Using Amit's answer I managed to find a solution. 使用Amit的答案,我设法找到了解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM