转自:http://developer.51cto.com/art/201202/317544.htm
上一篇文章说到怎样写一个最简单的Java Socket通信,但是在上一篇文章中的例子有一个问题就是Server只能接受一个Client请求,当第一个Client连接后就占据了这个位置,后续Client不能再继续连接,所以需要做些改动,当Server没接受到一个Client连接请求之后,都把处理流程放到一个独立的线程里去运行,然后等待下一个Client连接请求,这样就不会阻塞Server端接收请求了。每个独立运行的程序在使用完Socket对象之后要将其关闭。
1 package com.googlecode.garbagecan.test.socket.sample2; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.io.PrintWriter; 7 import java.net.ServerSocket; 8 import java.net.Socket; 9 10 public class MyServer { 11 public static void main(String[] args) throws IOException { 12 ServerSocket server = new ServerSocket(10000); 13 14 while (true) { 15 Socket socket = server.accept(); 16 invoke(socket); 17 } 18 } 19 20 private static void invoke(final Socket client) throws IOException { 21 new Thread(new Runnable() { 22 public void run() { 23 BufferedReader in = null; 24 PrintWriter out = null; 25 try { 26 in = new BufferedReader(new InputStreamReader(client.getInputStream())); 27 out = new PrintWriter(client.getOutputStream()); 28 29 while (true) { 30 String msg = in.readLine(); 31 System.out.println(msg); 32 out.println("Server received " + msg); 33 out.flush(); 34 if (msg.equals("bye")) { 35 break; 36 } 37 } 38 } catch(IOException ex) { 39 ex.printStackTrace(); 40 } finally { 41 try { 42 in.close(); 43 } catch (Exception e) {} 44 try { 45 out.close(); 46 } catch (Exception e) {} 47 try { 48 client.close(); 49 } catch (Exception e) {} 50 } 51 } 52 }).start(); 53 } 54 }
下面是Client程序代码:
1 package com.googlecode.garbagecan.test.socket.sample2; 2 3 import java.io.BufferedReader; 4 import java.io.InputStreamReader; 5 import java.io.PrintWriter; 6 import java.net.Socket; 7 8 public class MyClient { 9 public static void main(String[] args) throws Exception { 10 Socket socket = new Socket("localhost", 10000); 11 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 12 PrintWriter out = new PrintWriter(socket.getOutputStream()); 13 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 14 15 while (true) { 16 String msg = reader.readLine(); 17 out.println(msg); 18 out.flush(); 19 if (msg.equals("bye")) { 20 break; 21 } 22 System.out.println(in.readLine()); 23 } 24 socket.close(); 25 } 26 }
测试,首先运行MyServer类,然后运行两个MyClient类,然后分别在每个MyClient的提示符下输入字符串,就可以看到Server可以分别接收处理每个Client的请求了。