在上一篇文章中http://www.cnblogs.com/gosaint/p/8494423.html 我自定义了线程池ThreadPool。现在在我的EchoServer中使用自定义线程池去负责和客户端的通讯,代码如下所示:
package com.asiaInfo.caozg.ch_03.threadPool; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class EchoServerThread { private int port = 8000; private ServerSocket serverSocket; private ThreadPool threadPool;//线程池 private static final int POOLSIZE=4;//单个CPU时的线程的数目 public EchoServerThread() throws IOException { serverSocket = new ServerSocket(port); //创建线程池 //Runtime.getRuntime().availableProcessors()获取当前CPU的数目 threadPool=new ThreadPool(Runtime.getRuntime().availableProcessors()*POOLSIZE); System.out.println("服务器启动"); } public void service() { while (true) { Socket socket = null; try { socket = serverSocket.accept(); //等待客户连接 // 为每一个客户端创建一个线程 threadPool.execute(new Handles(socket));//把与客户端通信的任务交给线程池 } catch (IOException e) { e.printStackTrace(); } } } public static void main(String args[]) throws IOException { new EchoServerThread().service(); } private class Handles implements Runnable { private Socket socket; public Handles(final Socket socket) { this.socket = socket; } public String echo(String msg) { return "echo:" + msg; } private PrintWriter getWriter(Socket socket) throws IOException { OutputStream socketOut = socket.getOutputStream(); return new PrintWriter(socketOut, true); } private BufferedReader getReader(Socket socket) throws IOException { InputStream socketIn = socket.getInputStream(); return new BufferedReader(new InputStreamReader(socketIn)); } @Override public void run() { try { System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort()); BufferedReader br = getReader(socket); PrintWriter pw = getWriter(socket); String msg = null; while ((msg = br.readLine()) != null) { System.out.println(msg); pw.println(echo(msg)); if (msg.equals("bye")) //如果客户发送的消息为“bye”,就结束通信 break; } } catch (Exception e) { e.printStackTrace(); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
原文地址:https://www.cnblogs.com/gosaint/p/8505515.html
时间: 2024-10-25 05:01:00