java socket编程收藏之四(线程池)

(1)Server端 
Java代码   收藏代码
  1. import java.io.*;  
  2. import java.net.*;  
  3. public class PooledRemoteFileServer {  
  4.    //服务器能同时处理的活动客户机连接的最大数目  
  5.     protected int maxConnections;  
  6.    //进入的连接的侦听端口  
  7.     protected int listenPort;  
  8.     //将接受客户机连接请求的 ServerSocket   
  9.     protected ServerSocket serverSocket;  
  10.     public PooledRemoteFileServer(int aListenPort, int maxConnections) {  
  11.         listenPort= aListenPort;  
  12.         this.maxConnections = maxConnections;  
  13.     }  
  14.     public void acceptConnections() {  
  15.         try {  
  16.             ServerSocket server = new ServerSocket(listenPort, 5);  
  17.             Socket incomingConnection = null;  
  18.             while(true) {  
  19.                 incomingConnection = server.accept();  
  20.                 handleConnection(incomingConnection);  
  21.             }  
  22.         }  
  23.         catch(BindException e) {  
  24.             System.out.println("");  
  25.         }  
  26.         catch(IOException e) {  
  27.             System.out.println(""+listenPort);  
  28.         }  
  29.     }  
  30.       
  31.     /** 
  32.      * 委派PooledConnectionHandler处理连接 
  33.      */  
  34.     protected void handleConnection(Socket connectionToHandle) {  
  35.         PooledConnectionHandler.processRequest(connectionToHandle);  
  36.     }  
  37.       
  38.     /** 
  39.      * 创建maxConnections个PooledConnectionHandler并在新Thread中激活它们。 
  40.      * PooledConnectionHandler将等着处理进入的连接,每个都在它自己的Thread中进行。 
  41.      */  
  42.     public void setUpHandlers() {  
  43.         for(int i=0; i<maxConnections; i++) {  
  44.             PooledConnectionHandler currentHandler = new PooledConnectionHandler();  
  45.             new Thread(currentHandler, "Handler " + i).start();  
  46.         }  
  47.     }  
  48.     public static void main(String args[]) {  
  49.         PooledRemoteFileServer server = new PooledRemoteFileServer(10013);  
  50.         server.setUpHandlers();   
  51.         server.acceptConnections();  
  52.     }  
  53. }  


(2)实现线程池的类 
Java代码   收藏代码
  1. import java.io.*;  
  2. import java.net.*;  
  3. import java.util.*;  
  4. public class PooledConnectionHandler implements Runnable {  
  5.     //connection是当前正在处理的 Socket   
  6.     protected Socket connection;  
  7.     //静态 LinkedList 保存需被处理的连接,工作队列  
  8.     protected static List pool = new LinkedList();  
  9.     public PooledConnectionHandler() {}  
  10.     /** 
  11.      * 将攫取连接的流,使用它们,并在任务完成之后清除它们 
  12.      */  
  13.     public void  handleConnection() {  
  14.         try {  
  15.             PrintWriter streamWriter = new PrintWriter(connection.getOutputStream());   
  16.             BufferedReader streamReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));   
  17.             String fileToRead = streamReader.readLine();  
  18.             BufferedReader fileReader = new BufferedReader(new FileReader(fileToRead));  
  19.             String line = null;  
  20.             while((line=fileReader.readLine())!=null)  
  21.                 streamWriter.println(line);   
  22.             fileReader.close();  
  23.             streamWriter.close();  
  24.             streamReader.close();  
  25.         }  
  26.         catch(FileNotFoundException e) {  
  27.             System.out.println("");  
  28.         }  
  29.         catch(IOException e) {  
  30.             System.out.println(""+e);  
  31.         }  
  32.     }  
  33.     /** 
  34.      * 将把传入请求添加到池中,并告诉其它正在等待的对象该池已经有一些内容 
  35.      * @param requestToHandle 
  36.      */   
  37.     @SuppressWarnings("unchecked")  
  38.     public static void processRequest(Socket requestToHandle) {  
  39.         //确保没有别人能跟我们同时修改连接池  
  40.         synchronized(pool) {  
  41.             //把传入的Socket添加到LinkedList的尾端  
  42.             pool.add(pool.size(), requestToHandle);  
  43.             //通知其它正在等待该池的Thread,池现在已经可用  
  44.             pool.notifyAll();  
  45.         }  
  46.     }  
  47.     public void run() {  
  48.         while(true) {  
  49.             synchronized(pool) {  
  50.                 while(pool.isEmpty()) {  
  51.                     try {  
  52.                         //对池上的wait()的调用释放锁,而wait()接着就在自己返回之前再次攫取该锁  
  53.                         pool.wait();//在连接池上等待,并且池中一有连接就处理它  
  54.                     }  
  55.                     catch(InterruptedException e) {  
  56.                         e.printStackTrace();   
  57.                     }  
  58.                 }  
  59.                 //恰巧碰上非空池的处理程序将跳出while(pool.isEmpty())循环并攫取池中的第一个连接  
  60.                 connection= (Socket)pool.remove(0);   
  61.             }  
  62.             handleConnection();  
  63.         }  
  64.     }  
  65. }  

(3)Client端 
Java代码   收藏代码
  1. import java.io.*;  
  2. import java.net.*;  
  3. /** 
  4.  *   用您想连接的机器的 IP 地址和端口实例化 Socket。 
  5.  *   获取 Socket 上的流以进行读写。 
  6.  *   把流包装进 BufferedReader/PrintWriter 的实例,如果这样做能使事情更简单的话。 
  7.  *   对 Socket 进行读写。 
  8.  *   关闭打开的流。  
  9.  * @author Administrator 
  10.  */  
  11. public class RemoteFileClient {  
  12.     protected BufferedReader socketReader;  
  13.     protected PrintWriter socketWriter;  
  14.     protected String hostIp;  
  15.     protected int hostPort;  
  16.     /** 
  17.      * 构造方法 
  18.      */  
  19.     public RemoteFileClient(String hostIp, int hostPort) {  
  20.         this.hostIp = hostIp;  
  21.         this.hostPort=hostPort;   
  22.     }  
  23.     /** 
  24.      * 向服务器请求文件的内容,告诉服务器我们想要什么文件并在服务器传回其内容时接收该内容 
  25.      */  
  26.     public String getFile(String fileNameToGet) {  
  27.         StringBuffer fileLines = new StringBuffer();  
  28.         try {  
  29.             socketWriter.println(fileNameToGet);              
  30.             socketWriter.flush();  
  31.             String line = null;  
  32.             while((line=socketReader.readLine())!=null)  
  33.                 fileLines.append(line+"\n");  
  34.         }  
  35.         catch(IOException e) {  
  36.             System.out.println("Error reading from file: "+fileNameToGet);  
  37.         }  
  38.         return fileLines.toString();  
  39.     }  
  40.     /** 
  41.      * 连接到远程服务器,创建我们的 Socket 并让我们访问该套接字的流 
  42.      */  
  43.     public void setUpConnection() {  
  44.         try {  
  45.             Socket client = new Socket(hostIp,hostPort);  
  46.             socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));  
  47.             socketWriter = new PrintWriter(client.getOutputStream());  
  48.         }  
  49.         catch(UnknownHostException e) {  
  50.             System.out.println("Error1 setting up socket connection: unknown host at "+hostIp+":"+hostPort);  
  51.         }  
  52.         catch(IOException e) {  
  53.             System.out.println("Error2 setting up socket connection: "+e);  
  54.         }  
  55.     }  
  56.     /** 
  57.      * 使用完毕连接后负责“清除”。 
  58.      */  
  59.     public void tearDownConnection() {  
  60.         try {  
  61.             socketWriter.close();   
  62.             socketReader.close();  
  63.         }catch(IOException e) {              
  64.             System.out.println("Error tearing down socket connection: "+e);  
  65.         }  
  66.     }  
  67.     public static void main(String args[]) {  
  68.         RemoteFileClient remoteFileClient = new RemoteFileClient("127.0.0.1",1001);  
  69.         remoteFileClient.setUpConnection();  
  70.         StringBuffer fileContents = new StringBuffer();  
  71.         fileContents.append(remoteFileClient.getFile("D:/test.txt"));          
  72.         //remoteFileClient.tearDownConnection();  
  73.         System.out.println(fileContents);  
  74.     }  
  75. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值