Java Socket Client Connection pool

Source: Internet
Author: User
Tags nameserver

Recently due to the project needs, need to use the socket long connection server, but in the online search data found are the server connection pool, so I wrote a client socket connection pool, remember, for reference only, the meaning of the variable please replace, nonsense less, on the code.


1. Socet Information class

Package Cn.richinfo.cloudp.dm.common.util;import java.net.socket;/** * @Crop Shenzhen XXX Technology Co., Ltd. * @author Liuxingmi  * @QQ 63972012 * @DateTime 2014-8-25 pm 3:21:19  * @Desc Name server connection Information */public class Socketinfo {/** * socket */private socket SO cket;/** * Whether idle (yes: True  No: false) */private Boolean isfree;/** * Socket ID */private Integer socketid;/** * is a link that can be closed (yes : True  No: false) */private Boolean isclosed;public socket Getsocket () {return Socket;} public void Setsocket (socket socket) {this.socket = socket;} public Boolean Isfree () {return isfree;} public void Setfree (Boolean isfree) {this.isfree = Isfree;} Public Integer Getsocketid () {return socketid;} public void Setsocketid (Integer socketid) {this.socketid = Socketid;} public Boolean isClosed () {return isClosed;} public void setclosed (Boolean isClosed) {this.isclosed = isClosed;}}

2. Link Pooling Tool

Package Cn.richinfo.cloudp.dm.common.util;import Java.io.ioexception;import Java.net.socket;import java.util.Map; Import Java.util.concurrent.concurrenthashmap;import Cn.richinfo.cloudp.common.config.cloudpconfigutil;import Cn.richinfo.cloudp.common.constant.configconst;import cn.richinfo.cloudp.common.log.dmlogger;/** * @Crop Shenzhen XXXX Limited * @author LIUXINGMI * @QQ 63972012 * @DateTime 2014-8-25 PM 3:18:18 * @Desc Distributed Name server socket link Pool */public class S Ocketpool {private static Dmlogger logger = Dmlogger.getinstance ();//Log Class/** * Socketmap */public static Concurrenthashmap <integer, socketinfo> socketmap = new Concurrenthashmap<integer, socketinfo> ();p rivate static SocketPool Instance = new Socketpool ();p rivate socketpool () {}public static Socketpool getinstance () {if (instance = = null) { Synchronized (Socketpool.class) {if (instance = = null) {instance = new Socketpool ();}}} return instance;} static {Instance.initsocket (true);} /** * @DateTime 2014-8-25 pm 3:18:52 * @User Liuxingmi * Early @DescInitialize the link pool * @param isallreinit all reinitialization * @return void */public void Initsocket (Boolean isallreinit) {int defaultcount = int Eger.parseint (Configconst.socket_default_count); Logger.info ("Nameserver:initsocket", DMLogger.RESULT_OK, " Start initializing the number of distributed name server connections: "+ Defaultcount"; for (int i = 0; i < Defaultcount; i++) {if (isallreinit) {socketmap.put (I, Setsocketin Fo (I, true, false));} else {if (socketmap.get (i) = = NULL | | socketmap.get (i). isClosed ()) {Socketmap.put (I, Setsocketinfo (I, True, false));}} Logger.info ("Nameserver:initsocket", DMLOGGER.RESULT_OK, "completed initializing the number of distributed name server Connections"); new Checksocketthread (). Start (); /** * @DateTime 2014-8-26 a.m. 10:06:13 * @User Liuxingmi * @Desc Set socketinfo value * @param socket * @param key * @param isfre E * @param isClosed * @return socketinfo */private static socketinfo setsocketinfo (Integer key, Boolean Isfree, Boolean is Closed) {Socketinfo socketinfo = new Socketinfo (); Socket socket = Createsocket (); Socketinfo.setfree (Isfree); Socketinfo.setsocket (socket); Socketinfo.setsockeTId (key); socketinfo.setclosed (isClosed); return socketinfo;} /** * @DateTime 2014-8-25 pm 3:19:06 * @User Liuxingmi * @Desc Get Name Server link * @return * socketinfo */public Socketinfo gets Ocketinfo () {Socketinfo socketinfo = null;if (Socketmap.size () < Integer.parseint (Configconst.socket_default_count ) {Initsocket (false);} if (socketmap.size () > 0) {for (Map.entry<integer, socketinfo> entry:socketMap.entrySet ()) {Socketinfo = Entry.getvalue (); if (Socketinfo.isfree () &&! socketinfo.getsocket (). isClosed ()) {Socketinfo.setfree (false) ; return socketinfo;}}} else {logger.info ("Nameserver:socketinfo", Dmlogger.result_fail, "Name server socket connection pool number is zero.") "); return null;} Logger.info ("Nameserver:socketinfo", DMLOGGER.RESULT_OK, "All names server socket links are busy, create temporary links.") "); socketinfo = Setsocketinfo ( -1, True, true); Logger.info (" Nameserver:socketinfo ", DMLOGGER.RESULT_OK," Successfully created the server socket temporary link. "); return socketinfo;} /** * Release socket * @param socketid */public static void Distorysocket (Integer socketid) {logger.debug ("NamEserver:distorysocket ", DMLOGGER.RESULT_OK," release the name server socket link. "); Socketinfo socketinfo = Socketmap.get (Socketid); Socketinfo.setfree (true);} /** * @DateTime 2014-8-25 pm 3:19:42 * @User Liuxingmi * @Desc Release socket * @param socketinfo * void */public static void D Istorysocket (Socketinfo socketinfo) {if (Socketinfo = = null) return;if (! socketinfo.isclosed ()) {Logger.debug (" Nameserver:distorysocket ", DMLOGGER.RESULT_OK," link pool socket, release resources. ");d Istorysocket (Socketinfo.getsocketid ()); return;} Logger.debug ("Nameserver:distorysocket", DMLOGGER.RESULT_OK, "can close the temporary link, close the socket"); try {if (Socketinfo.getsocket ()! = NULL) {Socketinfo.getsocket (). Close ();}} catch (IOException e) {logger.error ("Nameserver:distorysocket", Dmlogger.result_fail, "Close name server socket failed", e);} Socketinfo = null;} /** * @DateTime 2014-8-25 pm 3:19:51 * @User Liuxingmi * @Desc Create socket * @return * Socket */public static socket creates Ocket () {String nameServerip1 = CloudpConfigUtil.DM_CONFIG.getNameSerIP1 (); int namServerport1 = CloudpconfigUtil.DM_CONFIG.getNameSerPort1 (); String nameServerip2 = CloudpConfigUtil.DM_CONFIG.getNameSerIP2 (); int namServerport2 = Cloudpconfigutil.dm_ Config.getnameserport2 (); Socket socket = null;try {//try to establish connection via IP1 for the first time socket = new socket (nameServerip1, namServerport1); Logger.info ("NameServer: Login ", DMLOGGER.RESULT_OK," nameServerip1: "+ nameServerip1 +", NamServerport1: "+ NamServerport1);} catch (IOException e) {logger.error ("Nameserver:login", Dmlogger.result_fail, "First link FAIL nameServerip1:" +  NameServerip1 + ", NamServerport1:" + NamServerport1, E);  try {//If the connection failed for the first time through IP1, the second connection is made to the socket = new socket (NAMESERVERIP2, namServerport2); Logger.info ("Nameserver:login", Dmlogger.result_ok, "NAMESERVERIP2:" + nameServerip2 + ", NamServerport2:" +     NAMSERVERPORT2); } catch (IOException E1) {logger.error ("Nameserver:login", Dmlogger.result_fail, "Second link FAIL nameServerip2:" + N    AmeServerip2 + ", NamServerport2:" + NamServerport2, E);     return null; }}return socket;} Class Checksocketthread extends thread{@Overridepublic void Run () {while (true) {Logger.debug ("Nameserver:checksocket", DMLOGGER.RESULT_OK, "Start detecting Distributed link status. "), if (Socketmap.size () < Integer.parseint (Configconst.socket_default_count)) {Logger.info (" NameServer: Checksocket ", DMLOGGER.RESULT_OK," The Distributed Name server socket link is less than the default number of links, increasing the socket link. "); Initsocket (false);} For (Map.entry<integer, socketinfo> entry:socketMap.entrySet ()) {Socketinfo socketinfo = Entry.getvalue (); if ( Socketinfo.getsocket () = = NULL | | Socketinfo.isclosed ()) {Logger.error ("Nameserver:checksocket", Dmlogger.result_fail, "first" + entry.getkey () + " A socket link is closed and the connection is reconnected. ", null); Socketinfo.setsocket (Createsocket ());} else {if (Socketinfo.isfree ()) {Boolean flag = Nameserverutils.getinstance (). Checkheartbeat (Socketinfo); if (! Flag) { Logger.error ("Nameserver:checksocket", Dmlogger.result_fail, "first" + entry.getkey () + "Socket link failed, reconnection distributed. ", null); Socketinfo.setsocket (Createsocket ()); continue;}} Logger.debug ("Nameserver:checksocket", Dmlogger.result_OK, "First" + entry.getkey () + "socket link is OK. ");}} try {sleep (long.valueof (Configconst.socket_check_time));} catch (Exception e) {}}}}


Java Socket Client Connection pool

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.