How to Implement Socket heartbeat packets and socket heartbeat packets
A client has been created recently, but a disconnection detection function is required. Let's take a look at using the custom HeartBeat method to check the client connection.
How to Implement heartbeat packets:
After the client is connected to the server, the server maintains an online client list. The client sends a heartbeat packet to the server at intervals. After receiving the packet, the server updates the last online time of the client. Once the server does not receive the package sent from the client after the specified time, it is deemed as a disconnection.
Code:
The client sends a heartbeat packet at intervals:
Var timer = new System. timers. timer (); timer. interval = 60000; // One timer is triggered at 1 Mbit/s. start (); timer. elapsed + = (sender, args) => {Console. writeLine ("start sending heartbeat packet"); MMessage message = new MMessage (); message. messageType = MessagePicks. heartbeat; // message. from = loginName; WriteToStream (message );};
Server Detection at intervals:
Var timer = new Timer (); timer. interval = 60000; // One timer is triggered at 1 Mbit/s. start (); timer. elapsed + = (sender, args) =>{ List <MClient> offClients = new List <MClient> (); foreach (var client in clients) {if (DateTime. now-client. lastOnLine ). totalMinutes> 1) {Console. writeLine ("user" + client. name + "dropped! "); OffClients. Add (client) ;}} foreach (var offClient in offClients) {clients. Remove (offClient );}};
The processing logic of the heartbeat packet received by the server:
Console. writeLine ("receive client" + msg. remoteEndPoint + "Heartbeat response packet. "); client. lastOnLine = DateTime. now; // receives the heartbeat packet and updates the client time. name = msg. remoteEndPoint. toString (); client. remoteEndPoint = msg. remoteEndPoint; if (! Clients. Contains (client) {clients. Add (client );}
Effect: