JAVA实现长连接(含心跳检测)Demo

实现原理:

       长连接的维持,是要客户端程序,定时向服务端程序,发送一个维持连接包的。
       如果,长时间未发送维持连接包,服务端程序将断开连接。

客户端:
       Client通过持有Socket的对象,可以随时(使用sendObject方法)发送Massage Object(消息)给服务端。
       如果keepAliveDelay毫秒(程序中是2秒)内未发送任何数据,则自动发送一个KeepAlive Object(心跳)给服务端,用于维持连接。
       由于,我们向服务端,可以发送很多不同的消息对象,服务端也可以返回不同的对象所以,对于返回对象的处理,要编写具体的ObjectAction实现类进行处理。通过Client.addActionMap方法进行添加。这样,程序会回调处理。

服务端:
        由于客户端会定时(keepAliveDelay毫秒)发送维持连接的信息过来,所以,服务端要有一个检测机制。
        即当服务端receiveTimeDelay毫秒(程序中是3秒)内未接收任何数据,则自动断开与客户端的连接。
         ActionMapping的原理与客户端相似(相同)。

         通过添加相应的ObjectAction实现类,可以实现不同对象的响应、应答过程。

Demo:

[html]  view plain  copy
  1. package socket.keepalive.test;  
  2.   
  3.   
  4. import java.io.Serializable;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.Date;  
  7.   
  8. /**  
  9.  *   
  10.  * 维持连接的消息对象(心跳对象)  
  11.  */  
  12. public class KeepAlive implements Serializable{  
  13.   
  14.     private static final long serialVersionUID = -2813120366138988480L;  
  15.   
  16.     /* 覆盖该方法,仅用于测试使用。  
  17.      * @see java.lang.Object#toString()  
  18.      */  
  19.     @Override  
  20.     public String toString() {  
  21.         return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"\t维持连接包";  
  22.     }  
  23.   
  24. }  

 

[html]  view plain  copy
  1. package socket.keepalive.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.ObjectInputStream;  
  6. import java.io.ObjectOutputStream;  
  7. import java.net.Socket;  
  8. import java.net.UnknownHostException;  
  9. import java.util.Collections;  
  10. import java.util.concurrent.ConcurrentHashMap;  
  11.   
  12. /**  
  13.  *  C/S架构的客户端对象,持有该对象,可以随时向服务端发送消息。  
  14.  * <p>  
  15.  * 创建时间:2010-7-18 上午12:17:25  
  16.  * @author HouLei  
  17.  * @since 1.0  
  18.  */  
  19. public class Client {  
  20.   
  21.     /**  
  22.      * 处理服务端发回的对象,可实现该接口。  
  23.      */  
  24.     public static interface ObjectAction{  
  25.         void doAction(Object obj,Client client);  
  26.     }  
  27.       
  28.     public static final class DefaultObjectAction implements ObjectAction{  
  29.         public void doAction(Object obj,Client client) {  
  30.             System.out.println("处理:\t"+obj.toString());  
  31.         }  
  32.     }  
  33.       
  34.       
  35.     public static void main(String[] args) throws UnknownHostException, IOException {  
  36.         String serverIp = "127.0.0.1";  
  37.         int port = 65432;  
  38.         Client client = new Client(serverIp,port);  
  39.         client.start();  
  40.     }  
  41.       
  42.     private String serverIp;  
  43.     private int port;  
  44.     private Socket socket;  
  45.     private boolean running=false; //连接状态  
  46.       
  47.     private long lastSendTime; //最后一次发送数据的时间  
  48.       
  49.     //用于保存接收消息对象类型及该类型消息处理的对象  
  50.     private ConcurrentHashMap<Class, ObjectAction> actionMapping = new ConcurrentHashMap<Class,ObjectAction>();  
  51.       
  52.     public Client(String serverIp, int port) {  
  53.         this.serverIp=serverIp;  
  54.         this.port=port;  
  55.     }  
  56.       
  57.     public void start() throws UnknownHostException, IOException {  
  58.         if(running)return;  
  59.         socket = new Socket(serverIp,port);  
  60.         System.out.println("本地端口:"+socket.getLocalPort());  
  61.         lastSendTime=System.currentTimeMillis();  
  62.         running=true;  
  63.         new Thread(new KeepAliveWatchDog()).start();  //保持长连接的线程,每隔2秒项服务器发一个一个保持连接的心跳消息  
  64.         new Thread(new ReceiveWatchDog()).start();    //接受消息的线程,处理消息  
  65.     }  
  66.       
  67.     public void stop(){  
  68.         if(running)running=false;  
  69.     }  
  70.       
  71.     /**  
  72.      * 添加接收对象的处理对象。  
  73.      * @param cls 待处理的对象,其所属的类。  
  74.      * @param action 处理过程对象。  
  75.      */  
  76.     public void addActionMap(Class<Object> cls,ObjectAction action){  
  77.         actionMapping.put(cls, action);  
  78.     }  
  79.   
  80.     public void sendObject(Object obj) throws IOException {  
  81.         ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());  
  82.         oos.writeObject(obj);  
  83.         System.out.println("发送:\t"+obj);  
  84.         oos.flush();  
  85.     }  
  86.       
  87.     class KeepAliveWatchDog implements Runnable{  
  88.         long checkDelay = 10;  
  89.         long keepAliveDelay = 2000;  
  90.         public void run() {  
  91.             while(running){  
  92.                 if(System.currentTimeMillis()-lastSendTime>keepAliveDelay){  
  93.                     try {  
  94.                         Client.this.sendObject(new KeepAlive());  
  95.                     } catch (IOException e) {  
  96.                         e.printStackTrace();  
  97.                         Client.this.stop();  
  98.                     }  
  99.                     lastSendTime = System.currentTimeMillis();  
  100.                 }else{  
  101.                     try {  
  102.                         Thread.sleep(checkDelay);  
  103.                     } catch (InterruptedException e) {  
  104.                         e.printStackTrace();  
  105.                         Client.this.stop();  
  106.                     }  
  107.                 }  
  108.             }  
  109.         }  
  110.     }  
  111.       
  112.     class ReceiveWatchDog implements Runnable{  
  113.         public void run() {  
  114.             while(running){  
  115.                 try {  
  116.                     InputStream in = socket.getInputStream();  
  117.                     if(in.available()>0){  
  118.                         ObjectInputStream ois = new ObjectInputStream(in);  
  119.                         Object obj = ois.readObject();  
  120.                         System.out.println("接收:\t"+obj);  
  121.                         ObjectAction oa = actionMapping.get(obj.getClass());  
  122.                         oa = oa==null?new DefaultObjectAction():oa;  
  123.                         oa.doAction(obj, Client.this);  
  124.                     }else{  
  125.                         Thread.sleep(10);  
  126.                     }  
  127.                 } catch (Exception e) {  
  128.                     e.printStackTrace();  
  129.                     Client.this.stop();  
  130.                 }   
  131.             }  
  132.         }  
  133.     }  
  134.       
  135. }  


 

[html]  view plain  copy
  1. package socket.keepalive.test;  
  2.   
  3.   
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.ObjectInputStream;  
  7. import java.io.ObjectOutputStream;  
  8. import java.net.ServerSocket;  
  9. import java.net.Socket;  
  10. import java.util.concurrent.ConcurrentHashMap;  
  11.   
  12. /**  
  13.  * C/S架构的服务端对象。  
  14.  * <p>  
  15.  * 创建时间:2010-7-18 上午12:17:37  
  16.  * @author HouLei  
  17.  * @since 1.0  
  18.  */  
  19. public class Server {  
  20.   
  21.     /**  
  22.      * 要处理客户端发来的对象,并返回一个对象,可实现该接口。  
  23.      */  
  24.     public interface ObjectAction{  
  25.         Object doAction(Object rev, Server server);  
  26.     }  
  27.       
  28.     public static final class DefaultObjectAction implements ObjectAction{  
  29.         public Object doAction(Object rev,Server server) {  
  30.             System.out.println("处理并返回:"+rev);  
  31.             return rev;  
  32.         }  
  33.     }  
  34.       
  35.     public static void main(String[] args) {  
  36.         int port = 65432;  
  37.         Server server = new Server(port);  
  38.         server.start();  
  39.     }  
  40.       
  41.     private int port;  
  42.     private volatile boolean running=false;  
  43.     private long receiveTimeDelay=3000;  
  44.     private ConcurrentHashMap<Class, ObjectAction> actionMapping = new ConcurrentHashMap<Class,ObjectAction>();  
  45.     private Thread connWatchDog;  
  46.       
  47.     public Server(int port) {  
  48.         this.port = port;  
  49.     }  
  50.   
  51.     public void start(){  
  52.         if(running)return;  
  53.         running=true;  
  54.         connWatchDog = new Thread(new ConnWatchDog());  
  55.         connWatchDog.start();  
  56.     }  
  57.       
  58.     @SuppressWarnings("deprecation")  
  59.     public void stop(){  
  60.         if(running)running=false;  
  61.         if(connWatchDog!=null)connWatchDog.stop();  
  62.     }  
  63.       
  64.     public void addActionMap(Class<Object> cls,ObjectAction action){  
  65.         actionMapping.put(cls, action);  
  66.     }  
  67.       
  68.     class ConnWatchDog implements Runnable{  
  69.         public void run(){  
  70.             try {  
  71.                 ServerSocket ss = new ServerSocket(port,5);  
  72.                 while(running){  
  73.                     Socket s = ss.accept();  
  74.                     new Thread(new SocketAction(s)).start();  
  75.                 }  
  76.             } catch (IOException e) {  
  77.                 e.printStackTrace();  
  78.                 Server.this.stop();  
  79.             }  
  80.               
  81.         }  
  82.     }  
  83.       
  84.     class SocketAction implements Runnable{  
  85.         Socket s;  
  86.         boolean run=true;  
  87.         long lastReceiveTime = System.currentTimeMillis();  
  88.         public SocketAction(Socket s) {  
  89.             this.s = s;  
  90.         }  
  91.         public void run() {  
  92.             while(running && run){  
  93.                 if(System.currentTimeMillis()-lastReceiveTime>receiveTimeDelay){  
  94.                     overThis();  
  95.                 }else{  
  96.                     try {  
  97.                         InputStream in = s.getInputStream();  
  98.                         if(in.available()>0){  
  99.                             ObjectInputStream ois = new ObjectInputStream(in);  
  100.                             Object obj = ois.readObject();  
  101.                             lastReceiveTime = System.currentTimeMillis();  
  102.                             System.out.println("接收:\t"+obj);  
  103.                             ObjectAction oa = actionMapping.get(obj.getClass());  
  104.                             oa = oa==null?new DefaultObjectAction():oa;  
  105.                             Object out = oa.doAction(obj,Server.this);  
  106.                             if(out!=null){  
  107.                                 ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());  
  108.                                 oos.writeObject(out);  
  109.                                 oos.flush();  
  110.                             }  
  111.                         }else{  
  112.                             Thread.sleep(10);  
  113.                         }  
  114.                     } catch (Exception e) {  
  115.                         e.printStackTrace();  
  116.                         overThis();  
  117.                     }   
  118.                 }  
  119.             }  
  120.         }  
  121.           
  122.         private void overThis() {  
  123.             if(run)run=false;  
  124.             if(s!=null){  
  125.                 try {  
  126.                     s.close();  
  127.                 } catch (IOException e) {  
  128.                     e.printStackTrace();  
  129.                 }  
  130.             }  
  131.             System.out.println("关闭:"+s.getRemoteSocketAddress());  
  132.         }  
  133.           
  134.     }  
  135.       
  136. }  

你可能感兴趣的:(架构设计)