- 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:

- .NET之美:.NET關鍵技術深入解析
- Mastering RabbitMQ
- Kubernetes實戰
- Beginning Java Data Structures and Algorithms
- Docker進階與實戰
- Java程序設計與計算思維
- Hands-On Automation Testing with Java for Beginners
- 人人都能開發RPA機器人:UiPath從入門到實戰
- Learning TypeScript
- Java EE輕量級解決方案:S2SH
- Learning iOS Penetration Testing
- JavaScript語法簡明手冊
- SAP HANA Cookbook
- 像程序員一樣使用MySQL
- R High Performance Programming