Use a connection pool in Java to manage a Socket

Source: Internet
Author: User

/**
*
*/
Package com. duoguo. util;
Import java. io. BufferedReader;
Import java. io. FileReader;
Import java. io. IOException;
Import java. io. InputStreamReader;
Import java. io. PrintWriter;
Import java.net. Socket;
Import java. util. Collections list;
Import java. util. List;
/**
* @ Author shyboy (chao.shen@duoguo.cn)
*
*/
Public class ConnectionPoolHandler implements Runnable {
Private Socket socket;
@ SuppressWarnings ("unchecked ")
Private static List pool = new writable List ();
/**
* Process connections
*/
Public void handleConnection (){
Try {
PrintWriter out = new PrintWriter (socket. getOutputStream ());
BufferedReader in = new BufferedReader (new InputStreamReader (socket
. GetInputStream ()));
String line = in. readLine ();
BufferedReader bufferedReader = new BufferedReader (new FileReader (
Line ));
String value = null;
While (value = bufferedReader. readLine ())! = Null ){
Out. println (value );
}
BufferedReader. close ();
Out. close ();
In. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
@ SuppressWarnings ("unchecked ")
Public static void processRequest (Socket socket ){
Synchronized (pool ){
Pool. add (pool. size (), socket );
Pool. policyall ();
}
}
/*
* (Non-Javadoc)
*
* @ See java. lang. Runnable # run ()
*/
@ Override
Public void run (){
While (true ){
Synchronized (pool ){
While (pool. isEmpty ()){
Try {
Pool. wait ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
Socket = (Socket) pool. remove (0 );
}
HandleConnection ();
}
}
}
 
/**
*
*/
Package com. duoguo. socket;
Import java. io. IOException;
Import java.net. ServerSocket;
Import java.net. Socket;
Import com. duoguo. util. ConnectionPoolHandler;
/**
* @ Author shyboy (chao.shen@duoguo.cn)
*
*/
Public class PoolMultiServer {
Private int maxConnections; // maximum number of connections
Private int listenerPort; // listening port number
Private ServerSocket serverSocket;
/**
* Constructor
*
* @ Param maxConnections
*: Maximum number of connections
* @ Param listenerPort
*: Listening port number
*/
Public PoolMultiServer (int maxConnections, int listenerPort ){
This. maxConnections = maxConnections;
This. listenerPort = listenerPort;
}
/**
* Accept connections
*/
Public void acceptConnection (){
Try {
ServerSocket = new ServerSocket (listenerPort, maxConnections );
While (true ){
Socket socket = serverSocket. accept ();
HandleConnection (socket );
}
} Catch (IOException e ){
E. printStackTrace ();
}
}
/**
* Process connections
*
* @ Param socket
*: Socket
*/
Public void handleConnection (Socket socket ){
ConnectionPoolHandler. processRequest (socket );
}
Public void setUpHandlers (){
For (int I = 0; I <maxConnections; I ++ ){
ConnectionPoolHandler connectionPoolHandler = new ConnectionPoolHandler ();
New Thread (connectionPoolHandler, "processor" + I). start ();
}
}
/**
* @ Param args
*/
Public static void main (String [] args ){
PoolMultiServer poolMultiServer = new PoolMultiServer (5, 9999 );
PoolMultiServer. setUpHandlers ();
PoolMultiServer. acceptConnection ();
}
}
 
/**
*
*/
Package com. duoguo. socket;
Import java. io. BufferedReader;
Import java. io. IOException;
Import java. io. InputStreamReader;
Import java. io. PrintWriter;
Import java.net. Socket;
Import java.net. UnknownHostException;
/**
* @ Author shyboy (chao.shen@duoguo.cn)
*
*/
Public class Client {
Private String hostIp; // client host IP Address
Private int hostPort; // The port number of the client host.
Private BufferedReader in; // client input stream
Private PrintWriter out; // client output stream
/**
* Constructor
*
* @ Param hostip
*: IP Address
* @ Param hostPort
*: Port Number
*/
Public Client (String hostip, int hostPort ){
This. hostIp = hostip;
This. hostPort = hostPort;
}
/**
* Establish a connection
*/
Public void setUpConnection (){
Try {
Socket client = new Socket (hostIp, hostPort );
In = new BufferedReader (new InputStreamReader (client
. GetInputStream (); // client input stream
Out = new PrintWriter (client. getOutputStream (); // The output stream of the client
} Catch (UnknownHostException e ){
System. out. println ("the corresponding host cannot be found! ");
E. printStackTrace ();
} Catch (IOException e ){
System. out. println ("throw the corresponding stream exception information ");
E. printStackTrace ();
}
}
/**
* Getting files
*
* @ Param fileName
*: File Name
* @ Return String
*/
Public String getFile (String fileName ){
StringBuilder sb = new StringBuilder ();
Out. println (fileName );
Out. flush ();
String line = null;
Try {
System. out. println ("client connection successful! ");
While (line = in. readLine ())! = Null ){
Sb. append (line + "\ n ");
}
} Catch (IOException e ){
System. out. println ("An error occurred while reading the file! ");
E. printStackTrace ();
}
Return sb. toString ();
}
/**
* Disconnect
*/
Public void tearDownConnection (){
Try {
Out. close (); // close the output stream.
In. close (); // close the input stream
} Catch (IOException e ){
System. out. println ("disconnection failed! ");
E. printStackTrace ();
}
}
/**
* @ Param args
*/
Public static void main (String [] args ){
Client client = new Client ("127.0.0.1", 9999 );
Client. setUpConnection ();
String fileContent = client. getFile ("D :\\ hello.txt ");
System. out. println ("File Content:" + "\ n" + fileContent );
Client. tearDownConnection ();
}
}

Author: "shenjichao2009"
 

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.