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

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:

主站蜘蛛池模板: 加查县| 龙山县| 梁山县| 桦南县| 大新县| 额济纳旗| 左贡县| 镇赉县| 新宁县| 大关县| 横山县| 黄大仙区| 阿拉善左旗| 理塘县| 顺平县| 阿鲁科尔沁旗| 鄱阳县| 尤溪县| 南京市| 芜湖市| 青冈县| 宜春市| 进贤县| 德安县| 特克斯县| 安康市| 宜丰县| 涞水县| 泸西县| 上虞市| 黄龙县| 山东省| 沛县| 保靖县| 鄂温| 漯河市| 崇左市| 漳平市| 昌宁县| 濉溪县| 大英县|