如何在java中实现TCP连接池? [英] How to implement TCP connection pooling in java?

查看:210
本文介绍了如何在java中实现TCP连接池?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我设法在单个服务器和单个客户端之间建立连接,但现在我的新障碍是如何实现 TCP 在客户端在JAVA中的连接。我经历了许多网站,但最终没有找到有效的解决方案。这里是我用来获取连接到服务器的

  public class TCPIPCommunicator {

private final String MODULE =TCPIPCommunicator:;

//私有DeviceEntity deviceEntity;
private static InetAddress inetServer = null;
private static int devicePort = -1;
private Socket clientSocket;
private BufferedOutputStream outputStream;
private BufferedInputStream inputStream;
private static boolean isLinkActive = false;
private String IP =;

public TCPIPCommunicator(String IP,int devicePort){
this.IP = IP;
this.devicePort = devicePort;
initialize();
}

public static boolean isLinkActive(){
return isLinkActive;
}

public static void setLinkStatus(boolean status){
isLinkActive = status;
}

private void initialize(){
System.out.println(MODULE +Inside initialize());
setLinkStatus(false);
try {
inetServer = InetAddress.getByName(IP);
} catch(UnknownHostException uhe){
System.out.println(MODULE +创建inetaddress时出错,原因:+ uhe.getMessage());
}
System.out.println(MODULE +Connecting to - + inetServer.getHostAddress()+:+ devicePort);
establishConnection();

if(!isLinkActive()){
//sendNotification(TCPIPConstants.LINK_DOWN);
releaseResources();
// resumeLinkSanityHelper();
}
System.out.println(MODULE +out of initialize(),isLinkActive:+ isLinkActive());
}

public boolean establishConnection(){
boolean isConnected = false;
//获取到PMS服务器的连接。
if(inetServer!= null&& devicePort> 0){
try {
clientSocket = new Socket(inetServer,devicePort);
clientSocket.setKeepAlive(true);
} catch(ConnectException ce){
ce.printStackTrace();
setLinkStatus(false);
System.out.println(MODULE +Exception in initialize()+Couldnot Connect Server。原因:+ ce.getMessage());
} catch(异常e){
e.printStackTrace();
setLinkStatus(false);
System.out.println(MODULE +Exception in initialize()+while creating socket,Reason:+ e.getMessage());
}

//如果有连接,获取流。
if(clientSocket!= null&&!clientSocket.isClosed()){
System.out.println(MODULE +in initialize(),Got Socket Connection。
try {
outputStream = new BufferedOutputStream(clientSocket.getOutputStream());
} catch(Exception e){
e.printStackTrace();
outputStream = null;
setLinkStatus(false);
System.out.println(MODULE +Exception in initialize()while getting socket outputStream:+ e.getMessage());
}

if(outputStream!= null){
try {
inputStream = new BufferedInputStream(clientSocket.getInputStream());
} catch(Exception e){
setLinkStatus(false);
System.out.println(MODULE +Exception in initialize()+while get socket inputStream:+ e.getMessage());
}
setLinkStatus(true);
}
if(outputStream!= null&& inputStream!= null){
isConnected = true;
}
} else {
System.out.println(MODULE +in initialize(),Connection is closed or null。
setLinkStatus(false);
}
}
return isConnected;
}



public int writeData(byte [] msg){
int retValue = -1;
try {
if(isLinkActive()&&(outputStream!= null)){
System.out.println(MODULE +Writting data :::+ new String msg)+::::);
outputStream.write(msg); // ed
outputStream.flush();
retValue = 1;
} else {
System.out.println(MODULE +in writeData()link is down so status:+ retValue);
}
} catch(异常e){
e.printStackTrace();
retValue = -1;
System.out.println(MODULE +write()中的异常要发送的消息为+ new String(msg)+>+ e.getMessage());
}
if(retValue == -1& isActive()){
setLinkStatus(false);
//sendNotification(TCPIPConstants.LINK_DOWN);
// releaseResources();
// resumeLinkSanityHelper();
}
System.out.println(MODULE +in writeData()Write state for+ new String(msg)+:: - >+ retValue);
return retValue;
}

public String readData(){
System.out.println(MODULE +\tInside readDAta);
String response = null;
int bytesReceived = -1;
byte [] readBuffer = new byte [1024];
try {
long timetoread = System.currentTimeMillis();
if(inputStream == null ||!(isLinkActive())){
System.out.println(MODULE +Inputstream is null or link is down,returned null);
return null;
}

try {
System.out.println(Waiting to read data);
bytesReceived = inputStream.read(readBuffer);
System.out.println(MODULE +#Byte Received#+ bytesReceived);
} catch(Exception e){
e.printStackTrace();
System.out.println(MODULE +readData()中出错,原因:+ e.getMessage());
if(isLinkActive()){
setLinkStatus(false);
//sendNotification(TCPIPConstants.LINK_DOWN);
releaseResources();
// resumeLinkSanityHelper();
}
}
if(bytesReceived> 0){
response = new String(readBuffer,0,bytesReceived); // ed
timetoread = System.currentTimeMillis() - timetoread;
System.out.println(MODULE +Total Bytes Received:+ bytesReceived);
System.out.println(MODULE +Total Time Taken:+ timetoread);
System.out.println(MODULE +received data data:+ response.length());
System.out.println(MODULE +Data Received:####+ response +####);
} else {
//////////这里意味着TCP连接状态将CLOSE_WAIT
//////////因此释放连接。
System.out.println(MODULE +Releasing Resource,bytesReceived is <= 0:Total Bytes Received:+ bytesReceived);
if(isLinkActive()){
setLinkStatus(false);
//sendNotification(TCPIPConstants.LINK_DOWN);
releaseResources();
// resumeLinkSanityHelper();
}
System.out.println(MODULE +Resource has been released。);
}
} catch(Exception e){
e.printStackTrace();
System.out.println(MODULE +In catch:Data Received:####+ response +####);
System.out.println(MODULE +readdata():+ e);
} finally {
readBuffer = null;
}
返回响应;
}



public void releaseResources(){
System.out.println(MODULE +Releasing Resources ....);
try {
if(clientSocket!= null)
clientSocket.close();
} catch(Exception e){
System.out.println(MODULE +In releaseResources():Error closed socket。+ e.getMessage());
}
try {
if(inputStream!= null)
inputStream.close();

} catch(Exception e){
System.out.println(MODULE +In releaseResources():Error close inputStream。+ e.getMessage());
}

try {
if(outputStream!= null){
outputStream.close();
}
} catch(Exception e){
System.out.println(MODULE +in releaseResources():Error close outputStream。
}
System.out.println(MODULE +Resources Relased ...);
}



}

这里 establishConnection()方法将建立连接到服务器。

注意:我在考虑使用 ThreadPoolExecutor 但是因为要求是同步的,所以我放弃了使用它的想法。

解决方案

您可以创建一个变量 Set< Socket& sockets 来存储你创建的所有 clientSocket 。每次连接到服务器套接字时,都可以将客户端
套接字set。因此这个集合作为池。


Here, I managed to get a connection between a single server and single client but now my new hurdle is how to achieve a pool of TCP connections on client side in JAVA. I had gone through many sites but at the end no fruitful solution was found. Here the class which I had used for obtaining connection to a server

public class TCPIPCommunicator {

private final String MODULE="TCPIPCommunicator :";

//private DeviceEntity deviceEntity;
private static InetAddress inetServer = null;
private static int devicePort = -1;
private Socket clientSocket;
private BufferedOutputStream outputStream;
private BufferedInputStream inputStream;
private static boolean isLinkActive = false;
private String IP="";

public TCPIPCommunicator(String IP, int  devicePort) {
    this.IP=IP;
    this.devicePort=devicePort;
    initialize();
}

public static boolean isLinkActive(){
    return isLinkActive;
}

public static void setLinkStatus(boolean status){
    isLinkActive = status;
}

private void initialize() {
    System.out.println(MODULE+ "Inside initialize()" );
    setLinkStatus(false);
    try{
        inetServer = InetAddress.getByName(IP);
    }catch (UnknownHostException uhe) {
        System.out.println(MODULE+ "Error while creating inetaddress, Reason:"+uhe.getMessage());
    }
    System.out.println(MODULE+ "Connecting to - " +inetServer.getHostAddress() + ":" + devicePort);
    establishConnection();

        if(!isLinkActive()){
            //sendNotification(TCPIPConstants.LINK_DOWN);
            releaseResources();
            //resumeLinkSanityHelper();
        }
    System.out.println(MODULE+ "out of initialize(), isLinkActive :" + isLinkActive() );
}

public boolean establishConnection(){
    boolean isConnected = false;
    //Get the Connection to PMS Server.
    if(inetServer != null && devicePort > 0){
        try{
            clientSocket = new Socket(inetServer, devicePort);
            clientSocket.setKeepAlive(true);
        }catch(ConnectException ce){
            ce.printStackTrace();
            setLinkStatus(false);
            System.out.println(MODULE+ "Exception in initialize() " + "Couldnot Connect Server. Reason:"+ce.getMessage());
        }catch(Exception e){
            e.printStackTrace();
            setLinkStatus(false);           
            System.out.println(MODULE+ "Exception in initialize() " + "while creating socket ,Reason: " + e.getMessage());
        }

        //If got connection, Get the streams.
        if(clientSocket != null && !clientSocket.isClosed()){
            System.out.println(MODULE+ "in initialize(), Got Socket Connection." );
            try{
                outputStream = new BufferedOutputStream(clientSocket.getOutputStream());
            }catch(Exception e){
                e.printStackTrace();
                outputStream=null;
                setLinkStatus(false);
                System.out.println(MODULE+ "Exception in initialize() while getting socket outputStream : " + e.getMessage());
            }

            if(outputStream != null){
                try{
                    inputStream = new BufferedInputStream(clientSocket.getInputStream());
                }catch(Exception e){
                    setLinkStatus(false);
                    System.out.println(MODULE+ "Exception in initialize() " + "while getting socket inputStream : " + e.getMessage());
                }
                setLinkStatus(true);
            }
            if(outputStream != null && inputStream != null){
                isConnected = true;
            }
        }else{
            System.out.println(MODULE+ "in initialize(), Connection is closed or null." );
            setLinkStatus(false);
        }
    }
    return isConnected;
}



public int writeData(byte[] msg){
    int retValue = -1;
    try{
        if(isLinkActive() && (outputStream !=null)){
            System.out.println(MODULE+ "Writting data  ::::" + new String(msg)+ "::::");
            outputStream.write(msg);// ed
            outputStream.flush();
            retValue = 1;
        }else{
            System.out.println(MODULE+ " in writeData() link is down so status:" + retValue );
        }
    }catch(Exception e){
        e.printStackTrace();
        retValue = -1;
        System.out.println(MODULE+ "Exception in write() < message to be sent was = " + new String(msg) + " > : " + e.getMessage());
    }
    if(retValue == -1 && isLinkActive()){
        setLinkStatus(false);
        //sendNotification(TCPIPConstants.LINK_DOWN);
        //releaseResources();
        //resumeLinkSanityHelper();
    }
    System.out.println(MODULE+ " in writeData() Write status for ::"+ new String(msg) + ":: -->" +retValue);
    return retValue;
}

public String readData() {
    System.out.println(MODULE+"\tInside readDAta");
    String response = null;
    int bytesReceived=-1;
    byte[] readBuffer = new byte[1024];
    try{
        long timetoread = System.currentTimeMillis();
        if(inputStream == null || !(isLinkActive())){
            System.out.println(MODULE+"Inputstream is null or link is down, returning null");
            return null;
        }

        try{
            System.out.println("Waiting to read data");
            bytesReceived = inputStream.read(readBuffer);
            System.out.println(MODULE+"# Byte Receieved #" + bytesReceived);
        }catch(Exception e){
            e.printStackTrace();
            System.out.println(MODULE+"Error in readData() , Reason:"+e.getMessage());
            if(isLinkActive()){
                setLinkStatus(false);
                //sendNotification(TCPIPConstants.LINK_DOWN);
                releaseResources();
                //resumeLinkSanityHelper();
            }
        }
        if(bytesReceived > 0){          
            response = new String(readBuffer,0,bytesReceived); // ed
            timetoread = System.currentTimeMillis() - timetoread;
            System.out.println(MODULE + "Total Bytes Received: " + bytesReceived);
            System.out.println(MODULE+ "Total Time Taken : " + timetoread);
            System.out.println(MODULE+ "Length of data received : " + response.length());
            System.out.println(MODULE+ "Data Received : ####" + response + "####");
        }else{
            ////////// HERE MEANS TCP CONNECTION STATUS WILL CLOSE_WAIT
            ////////// SO RELEASING CONNECTION.
            System.out.println(MODULE+ " Releasing Resource. bytesReceived is <= 0 : Total Bytes Received :"+ bytesReceived );
            if(isLinkActive()){
                setLinkStatus(false);
                //sendNotification(TCPIPConstants.LINK_DOWN);
                releaseResources();
                //resumeLinkSanityHelper();
            }
            System.out.println(MODULE+ " Resource has been released.");
        }
    }catch(Exception e){
        e.printStackTrace();
        System.out.println(MODULE+ "In catch : Data Received : ####" + response + "####");
        System.out.println(MODULE+ "Exception in readdata() : " + e);
    }finally{
        readBuffer=null;
    }
    return response;
}



public void releaseResources(){
    System.out.println(MODULE+ "Releasing Resources....");
    try{
        if(clientSocket !=null)
            clientSocket.close();
    }catch(Exception e){
        System.out.println(MODULE+ "In releaseResources() :Error closing socket."+e.getMessage());
    }
    try{
        if(inputStream !=null )
            inputStream.close();

    }catch(Exception e){
        System.out.println(MODULE+ "In releaseResources() :Error closing inputStream."+e.getMessage());         
    }

    try{
        if(outputStream != null){
            outputStream.close();
        }
    }catch(Exception e){
        System.out.println(MODULE+ "in releaseResources() :Error closing outputStream.");
    }
    System.out.println(MODULE + "Resources Relased...");        
}



}

Here establishConnection() method will be establish the connection to the server. Any help would be a tons of help.

Note: I was thinking on using ThreadPoolExecutor but as the requirement is for synchronous so I dropped this idea of using it.

解决方案

You can create a variable Set<Socket> sockets to store all the clientSocket you created.Every time you connect to the server socket, you can put the client socket into this set.So this set works as the pool.

这篇关于如何在java中实现TCP连接池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆