官术网_书友最值得收藏!

Using the disconnect event

Our app is only capturing connection and joining events. Remember that the connection happens automatically, as we do not check the client at all. As soon as the client's io.connect() is called, a connection event is fired. Then, when we change the text input, a join event is fired, which goes to all the other clients. Nothing happens when someone leaves.

Socket disconnection events are different than regular HTTP events. Because HTTP is request based, we never really know when someone leaves; we just know what their last request was. Users usually have to take an action to leave, for example, going to the logout page. Socket.IO creates and maintains a persistent connection, so we will know immediately when someone leaves. Let's add it to our application.

We will begin at the backend. Open app.js and add a new listener for the disconnect event:

socket.on('disconnect', function(){
    socket.broadcast.emit('userDisconnect', {username: socket.username});
  });

There isn't really too much that is new. We know about event listeners, how to get data attached to a socket, and how to broadcast it to everyone but yourself.

Now, we have to go to the client and add the listener there. Add the following to our list of functions:

socket.on('userDisconnect', function(data){
    addLi(data.username + ' has left :(');
});

This function is similar to the others we have written. It just takes the passed in username and adds a new list item to the list. Connect some users and then refresh the page, and you should get some disconnection events, which are shown in the following screenshot:

主站蜘蛛池模板: 新巴尔虎左旗| 剑川县| 灵宝市| 咸宁市| 湾仔区| 泗水县| 横峰县| 雷州市| 永登县| 平定县| 通州市| 樟树市| 宁波市| 利辛县| 额敏县| 镇沅| 尉犁县| 天镇县| 高清| 石林| 会宁县| 蓬安县| 顺昌县| 宁晋县| 双辽市| 中阳县| 安宁市| 古丈县| 丰都县| 聂荣县| 海伦市| 琼中| 延津县| 通化市| 桃江县| 民乐县| 龙井市| 华坪县| 临猗县| 新安县| 华宁县|