Socket.IO 处理断开事件 [英] Socket.IO handling disconnect event
本文介绍了Socket.IO 处理断开事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无法处理这个断开连接事件,不知道为什么socket没有发送到客户端/客户端没有响应!
Can't handle this disconnect event, don't know why socket is not sent to the client / client doesn't respond!
服务器
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);
});
});
如您所见,当客户端断开连接时,Array 对象 [person_name] 应该被删除,但事实并非如此.
As you can see when a client disconnects the Array object[person_name] should be deleted, but it's 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 处理断开事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文