Java:server/client Heartbeat Mechanism Implementation Example

Source: Internet
Author: User

Heartbeat mechanism

The heartbeat mechanism is a mechanism that periodically sends a custom structure (heartbeat pack) that lets the other person know that they are still alive to ensure the validity of the connection.

Most CS applications require a heartbeat mechanism. The heartbeat mechanism is generally implemented in both the server and client, and the basic principle is the same. The client does not care about performance and can do whatever it takes.

If the application is TCP-based, the heartbeat can be achieved simply by so_keepalive. TCP sends a detection TCP segment to the peer when the set KeepAlive timer arrives, and if no ACK or RST is received, after several attempts, it is considered that the peer is no longer present and the application is finally notified. One drawback here is that the server proactively emits the detection packet, which has a slight impact on performance.

Apply your own implementation
The client initiates a timer, and the heartbeat is constantly sent;
After the server receives the heartbeat, give a response;
The server starts a timer to determine if the client exists, and the method of judging is listed here in two ways:
Time difference and simple sign.

    1. Time difference Strategy

      After you receive a heartbeat, record the current time (recorded as Recvedtime).

      Determine how long the timer time arrives and how much time is forfeited to the heartbeat (T) = Current Time-Recvedtime (the time recorded above). If T is greater than a certain value, you can assume that the client has timed out.

    2. Simple sign

      After receiving a heartbeat, set the connection flag to true;

      Determine the timer time arrives, view all the flags, false, think the peer timed out; true to set it to false.

      The above method is simpler than above, but the error of detecting whether a client is offline is a bit large.

Demo

Here we implement a sending object, the example is primitive, actually in the work also needs to revise according to the demand.

entity class
package com.lee.entity;import java.io.Serializable;public class Entity implements Serializable {    private static final long serialVersionUID = 1L;    private String name;    private String sex;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    @Override    public String toString() {        return "Entity [name=" + name + ", sex=" + sex + "]";    }}

Service side

serverheart.java
Package Com.lee.server;import Java.io.objectinput;import Java.io.objectinputstream;import java.net.ServerSocket; Import Java.net.socket;import Com.lee.entity.entity;public class Serverheart extends Thread {private ServerSocket serv    ER = null;    Object obj = new Object ();            @Override public void Run () {try {server = new ServerSocket (9090);                while (true) {Socket client = server.accept ();                Synchronized (obj) {new Thread (new client). Start ();        }}} catch (Exception e) {e.printstacktrace (); }}/** * Client thread * * @author USER * */class Client implements Runnable {Socket Clien        T        Public Client (Socket client) {this.client = client; } @Override public void Run () {try {while (true) {Objectinpu T in = new ObjectInputStream (client.geTinputstream ());                    Entity entity = (entity) In.readobject ();                SYSTEM.OUT.PRINTLN (entity);            }} catch (Exception e) {e.printstacktrace ();        }}}/** * The entry of the program Main method * @param args */public static void main (string[] args) {        System.out.println ("Start detecting if the client is online ...");    New Serverheart (). Start (); }}

Client

Clientheart.java
package com.lee.client;public class ClientHeart extends Thread {    @Override    public void run() {        try {            while (true) {                ClientSender.getInstance().send();                synchronized (ClientHeart.class) {                    // this.wait(5000);                    Thread.sleep(2000);                }            }        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 程序的入口main方法     *      * @param args     */    public static void main(String[] args) {        ClientHeart client = new ClientHeart();        client.start();    }}
Clientsender.java
Package Com.lee.client;import Java.io.objectoutputstream;import Java.net.inetaddress;import java.net.Socket;import    Com.lee.entity.entity;public class Clientsender {private Clientsender () {} Socket sender = null;    private static Clientsender instance;                public static Clientsender getinstance () {if (instance = = null) {synchronized (Clientheart.class) {            Instance = new Clientsender ();    }} return instance;            public void Send () {try {sender = new Socket (Inetaddress.getlocalhost (), 9090);                while (true) {objectoutputstream-out = new ObjectOutputStream (Sender.getoutputstream ());                Entity obj = new entity ();                Obj.setname ("Xiaoming");                Obj.setsex ("male");                Out.writeobject (obj);                Out.flush ();                SYSTEM.OUT.PRINTLN ("Sent ...");            Thread.Sleep (5000); }} catch (Exception e) {}}} 

Java:server/client Heartbeat Mechanism Implementation Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.