- Building Scalable Apps with Redis and Node.js
- Joshua Johanan
- 262字
- 2021-08-05 17:49:05
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:

- Java程序設(shè)計(jì)與開發(fā)
- C++程序設(shè)計(jì)(第3版)
- 精通搜索分析
- PyTorch自然語(yǔ)言處理入門與實(shí)戰(zhàn)
- Scratch 3.0少兒編程與邏輯思維訓(xùn)練
- Linux環(huán)境編程:從應(yīng)用到內(nèi)核
- 用Python實(shí)現(xiàn)深度學(xué)習(xí)框架
- Java程序員面試筆試寶典(第2版)
- HTML5開發(fā)精要與實(shí)例詳解
- Learning AWS
- 計(jì)算機(jī)應(yīng)用技能實(shí)訓(xùn)教程
- Python 3快速入門與實(shí)戰(zhàn)
- AI輔助編程Python實(shí)戰(zhàn):基于GitHub Copilot和ChatGPT
- 軟件測(cè)試項(xiàng)目實(shí)戰(zhàn)之功能測(cè)試篇
- Selenium自動(dòng)化測(cè)試實(shí)戰(zhàn):基于Python