本文介绍了Socket.IO处理断开事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法处理此断开连接事件,不知道为什么socket不发送给客户端/客户端没有响应!

Cant handle this disconnect event, dont know why socket its not send to the client / client doesnt response!

服务器

io.sockets.on('connection', function (socket) {

  socket.on('NewPlayer', function(data1) {

    online = online + 1;
    console.log('Online players : ' + online);
    console.log('New player connected : ' + data1);
    Players[data1] = data1;
    console.log(Players);

  });

  socket.on('DelPlayer', function(data) {

    delete Players[data];
    console.log(Players);
    console.log('Adios' + data);

  });

  socket.on('disconnect', function () {

      socket.emit('disconnected');
      online = online - 1;

  });

});

客户

 var socket = io.connect('http://localhost');

    socket.on('connect', function () {

        person_name = prompt("Welcome. Please enter your name");

        socket.emit('NewPlayer', person_name);

        socket.on('disconnected', function() {

            socket.emit('DelPlayer', person_name);

        });

    });

正如您所看到的,当客户端断开连接时,应该删除数组对象[person_name],但不是

As you can see when a client disconnects the Array object[person_name] should be deleted, but its not

推荐答案

好的,不是通过名称跟踪识别玩家,而是通过他们连接的套接字。您可以拥有类似

Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like

var allClients = [];
io.sockets.on('connection', function(socket) {
   allClients.push(socket);

   socket.on('disconnect', function() {
      console.log('Got disconnect!');

      var i = allClients.indexOf(socket);
      allClients.splice(i, 1);
   });
});

希望这会帮助你以另一种方式思考

Hope this will help you to think in another way

这篇关于Socket.IO处理断开事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 16:34