Program Tip

연결 해제 이벤트를 처리하는 Socket.IO

programtip 2020. 10. 18. 19:00
반응형

연결 해제 이벤트를 처리하는 Socket.IO


이 연결 끊기 이벤트를 처리 할 수 ​​없습니다. 소켓이 클라이언트에 전송되지 않는 이유를 알 수 없습니다. / 클라이언트가 응답하지 않습니다!

섬기는 사람

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]는 삭제되어야하지만 삭제되지 않아야합니다.


좋아, 플레이어가 연결된 소켓이있는 이름 트랙으로 플레이어를 식별하는 대신. 다음과 같은 구현을 가질 수 있습니다.

섬기는 사람

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

이것이 다른 방식으로 생각하는 데 도움이되기를 바랍니다.


@ sha1과 같은 사람들이 왜 OP의 코드가 작동하지 않는지 궁금해합니다.

서버 측에서 플레이어를 삭제하는 OP 로직은 DelPlayer이벤트 핸들러에 있으며,이 이벤트 ( DelPlayer) 를 발생시키는 코드 disconnected는 클라이언트의 이벤트 콜백 내부에 있습니다 .

The server side code that emits this disconnected event is inside the disconnect event callback which is fired when the socket loses connection. Since the socket already lost connection, disconnected event doesn't reach the client.


Accepted solution executes the logic on disconnect event at server side, which is fired when the socket disconnects, hence works.


Create a Map or a Set, and using "on connection" event set to it each connected socket, in reverse "once disconnect" event delete that socket from the Map we created earlier

import * as Server from 'socket.io';

const io = Server();
io.listen(3000);

const connections = new Set();

io.on('connection', function (s) {

  connections.add(s);

  s.once('disconnect', function () {
    connections.delete(s);
  });

});

참고URL : https://stackoverflow.com/questions/17287330/socket-io-handling-disconnect-event

반응형