Java Socket Long Connection

Source: Internet
Author: User

Package com.paic.umap.tcp;  Import java.io.IOException;  Import Java.io.InputStream;  Import Java.io.ObjectInputStream;  Import Java.io.ObjectOutputStream;  Import Java.net.ServerSocket;  Import Java.net.Socket;    Import Java.util.concurrent.ConcurrentHashMap;  /** * Server-side object for the C/s architecture.      * <p> * @since 1.0 */public class Server {/** * To process the object sent by the client and return an object to implement the interface.      */public Interface objectaction{Object DoAction (object rev);  public static final class Defaultobjectaction implements objectaction{public object DoAction (object              Rev) {System.out.println ("process and return:" +rev);          return rev;          }} public static void Main (string[] args) {int port = 65432;          Server server = new server (port);      Server.start ();      } private int port;      Private volatile Boolean running=false;      Private long receivetimedelay=3000; Private CONCURRENTHASHMAP&LT;CLASS, Objectaction> actionmapping = new concurrenthashmap<class,objectaction> ();            Private Thread Connwatchdog;      public Server (int port) {this.port = port;          public void Start () {if (running) return;          Running=true;          Connwatchdog = new Thread (new Connwatchdog ());      Connwatchdog.start ();          } @SuppressWarnings ("deprecation") public void Stop () {if (running) Running=false;    if (connwatchdog!=null) connwatchdog.stop (); The public void Addactionmap (class<object> cls,objectaction action) {actionmapping.put (CLS, action      ); } class Connwatchdog implements runnable{public void run () {try {Serve                  Rsocket ss = new ServerSocket (port,5);                      while (running) {Socket s = ss.accept ();                  New Thread (new Socketaction (s)). Start (); }} catch (IOEXception e) {e.printstacktrace ();              Server.this.stop ();          }}} class Socketaction implements runnable{Socket s;          Boolean run=true;          Long lastreceivetime = System.currenttimemillis ();          Public Socketaction (Socket s) {this.s = s; public void Run () {running && run} {if (System.currenttimemillis ()-                  Lastreceivetime>receivetimedelay) {overthis ();                          }else{try {InputStream in = S.getinputstream ();                              if (in.available () >0) {ObjectInputStream ois = new ObjectInputStream (in);                              Object obj = Ois.readobject ();                              Lastreceivetime = System.currenttimemillis (); System.out.println ("Receive: \ T" +obj);                              Objectaction OA = Actionmapping.get (Obj.getclass ());                              OA = Oa==null?new defaultobjectaction (): OA;                              Object out = oa.doaction (obj);                                  if (out!=null) {ObjectOutputStream oos = new ObjectOutputStream (S.getoutputstream ());                                  Oos.writeobject (out);                              Oos.flush ();                          }}else{Thread.Sleep (10);                          }} catch (Exception e) {e.printstacktrace ();                      Overthis ();            }}}} private void Overthis () {if (run) Run=false;                  if (s!=null) {try {s.close ();           } catch (IOException e) {           E.printstacktrace ();          }} System.out.println ("Close:" +s.getremotesocketaddress ());   }                }        }

Package com.paic.umap.tcp;  Import java.io.IOException;  Import Java.io.InputStream;  Import Java.io.ObjectInputStream;  Import Java.io.ObjectOutputStream;  Import Java.net.Socket;  Import java.net.UnknownHostException;    Import Java.util.concurrent.ConcurrentHashMap;  /** * C/S Architecture client object that holds the object and can send messages to the server at any time.      * <p> * @since 1.0 */public class Client {/** * handles the object sent back by the server to implement the interface.      */public static interface Objectaction {void doAction (Object obj,client Client); } public static final class Defaultobjectaction implements objectaction {public void doAction (Object obj,clie          NT client) {System.out.println ("Processing: \ T" +obj.tostring ());      }} private String ServerIP;      private int port;      private socket socket;      Private Boolean running=false;      Private long lastsendtime; Private Concurrenthashmap<class, objectaction> actionmapping = new concurrenthashmap<class,objectaction>    ();        Public Client (String serverip, int port) {this.serverip=serverip;this.port=port;          } public void Start () throws Unknownhostexception, IOException {if (running) return;          Socket = new socket (serverip,port);          SYSTEM.OUT.PRINTLN ("Local Port:" +socket.getlocalport ());          Lastsendtime=system.currenttimemillis ();          Running=true;          New Thread (New Keepalivewatchdog ()). Start ();      New Thread (New Receivewatchdog ()). Start ();      } public void Stop () {if (running) Running=false;      }/** * Adds a processing object for the receiving object.      * @param CLS object to be processed, the class to which it belongs.      * @param action Process object.      */public void Addactionmap (class<object> cls,objectaction action) {actionmapping.put (CLS, action); } public void SendObject (Object obj) throws IOException {ObjectOutputStream Oos = new Objectoutputstr          EAM (Socket.getoutputstream ());          Oos.writeobject (obj); System.out.prIntln ("Send: \ t" +obj);      Oos.flush ();          } class Keepalivewatchdog implements Runnable {long checkdelay = 10;          Long Keepalivedelay = 2000; public void Run () {while (running) {if (System.currenttimemillis ()-lastsendtime>keepalived                      Elay) {try {Client.this.sendObject (New KeepAlive ());                          } catch (IOException e) {e.printstacktrace ();                      Client.this.stop ();                  } lastsendtime = System.currenttimemillis ();                      }else{try {thread.sleep (checkdelay);                          } catch (Interruptedexception e) {e.printstacktrace ();                      Client.this.stop (); }}}}} class Receivewatchdog implements RunnAble {public void run () {when (running) {try {InputStream in                      = Socket.getinputstream ();                          if (in.available () >0) {ObjectInputStream ois = new ObjectInputStream (in);                          Object obj = Ois.readobject ();                          System.out.println ("Receive: \ T" +obj);                          Objectaction OA = Actionmapping.get (Obj.getclass ());                          OA = Oa==null?new defaultobjectaction (): OA;                      Oa.doaction (obj, client.this);                      }else{Thread.Sleep (10);                      }} catch (Exception e) {e.printstacktrace ();                  Client.this.stop ();  }}}} public static void Main (string[] args) throws Unknownhostexception, IOException          {String ServerIP = "127.0.0.1"; Int Port = 65432;          Client client = new Client (serverip,port);      Client.start ();   } }

  

Package com.paic.umap.tcp;    Import Java.io.serializable;import java.text.simpledateformat;import java.util.Date;  /**  * maintains a connected Message object.  * <p>  * @since 1.0 */public  class KeepAlive implements serializable{        private static final Long serialversionuid = -2813120366138988480l;        /* Override this method and use it only for testing.      * @see java.lang.object#tostring ()      */      @Override public      String toString () {          return new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (new Date ()) + "\ t maintain connection package";      }    }  

  

Java Socket Long Connection

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.