多线程Java Socket编程
原文来自 http://www.blogjava.net/sterning/archive/2007/10/15/152940.html
服务器
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.InputStreamReader; 5 import java.io.OutputStream; 6 import java.io.PrintWriter; 7 import java.net.*; 8 import java.util.concurrent.*; 9 10 public class MultiThreadServer { 11 private int port=8821; 12 private ServerSocket serverSocket; 13 private ExecutorService executorService;//线程池 14 private final int POOL_SIZE=10;//单个CPU线程池大小 15 16 public MultiThreadServer() throws IOException{ 17 serverSocket=new ServerSocket(port); 18 //Runtime的availableProcessor()方法返回当前系统的CPU数目. 19 executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE); 20 System.out.println("服务器启动"); 21 } 22 23 public void service(){ 24 while(true){ 25 Socket socket=null; 26 try { 27 //接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接 28 socket=serverSocket.accept(); 29 executorService.execute(new Handler(socket)); 30 31 } catch (Exception e) { 32 e.printStackTrace(); 33 } 34 } 35 } 36 37 public static void main(String[] args) throws IOException { 38 new MultiThreadServer().service(); 39 } 40 41 } 42 43 class Handler implements Runnable{ 44 private Socket socket; 45 public Handler(Socket socket){ 46 this.socket=socket; 47 } 48 private PrintWriter getWriter(Socket socket) throws IOException{ 49 OutputStream socketOut=socket.getOutputStream(); 50 return new PrintWriter(socketOut,true); 51 } 52 private BufferedReader getReader(Socket socket) throws IOException{ 53 InputStream socketIn=socket.getInputStream(); 54 return new BufferedReader(new InputStreamReader(socketIn)); 55 } 56 public String echo(String msg){ 57 return "echo:"+msg; 58 } 59 public void run(){ 60 try { 61 System.out.println("New connection accepted "+socket.getInetAddress()+":"+socket.getPort()); 62 BufferedReader br=getReader(socket); 63 PrintWriter pw=getWriter(socket); 64 String msg=null; 65 while((msg=br.readLine())!=null){ 66 System.out.println(msg); 67 pw.println(echo(msg)); 68 if(msg.equals("bye")) 69 break; 70 } 71 } catch (IOException e) { 72 e.printStackTrace(); 73 }finally{ 74 try { 75 if(socket!=null) 76 socket.close(); 77 } catch (IOException e) { 78 e.printStackTrace(); 79 } 80 } 81 } 82 }
客户端
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.io.OutputStream; 5 import java.net.Socket; 6 import java.util.concurrent.ExecutorService; 7 import java.util.concurrent.Executors; 8 9 public class MultiThreadClient { 10 11 public static void main(String[] args) { 12 int numTasks = 10; 13 14 ExecutorService exec = Executors.newCachedThreadPool(); 15 16 for (int i = 0; i < numTasks; i++) { 17 exec.execute(createTask(i)); 18 } 19 20 } 21 22 // 定义一个简单的任务 23 private static Runnable createTask(final int taskID) { 24 return new Runnable() { 25 private Socket socket = null; 26 private int port=8821; 27 28 public void run() { 29 System.out.println("Task " + taskID + ":start"); 30 try { 31 socket = new Socket("localhost", port); 32 // 发送关闭命令 33 OutputStream socketOut = socket.getOutputStream(); 34 socketOut.write("shutdown\r\n".getBytes()); 35 36 // 接收服务器的反馈 37 BufferedReader br = new BufferedReader( 38 new InputStreamReader(socket.getInputStream())); 39 String msg = null; 40 while ((msg = br.readLine()) != null) 41 System.out.println(msg); 42 } catch (IOException e) { 43 e.printStackTrace(); 44 } 45 } 46 47 }; 48 } 49 }