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

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:

主站蜘蛛池模板: 上蔡县| 临猗县| 洪江市| 浮山县| 阳城县| 青河县| 安化县| 应用必备| 双桥区| 儋州市| 海盐县| 松桃| 平潭县| 临潭县| 仙游县| 巫溪县| 乌恰县| 新乡市| 通海县| 辽中县| 临洮县| 建瓯市| 石阡县| 全州县| 桃园市| 白山市| 年辖:市辖区| 莱阳市| 海晏县| 中超| 县级市| 陵水| 池州市| 永德县| 准格尔旗| 苍山县| 衡山县| 云龙县| 泾源县| 银川市| 望城县|