/* * 基於TCP協議的Socket通訊 * 服務器端 */ public class Server { public static void main(String[] args) { try { //1.建立一個服務器端Socket,即ServerSocket,指定綁定的端口,並監聽此端口 ServerSocket serverSocket=new ServerSocket(8888); Socket socket=null; //記錄客戶端的數量 int count=0; System.out.println("***服務器即將啓動,等待客戶端的鏈接***"); //循環監聽等待客戶端的鏈接 while(true){ //調用accept()方法開始監聽,等待客戶端的鏈接 socket=serverSocket.accept(); //建立一個新的線程 ServerThread serverThread=new ServerThread(socket); //啓動線程 serverThread.start(); count++;//統計客戶端的數量 System.out.println("客戶端的數量:"+count); InetAddress address=socket.getInetAddress(); System.out.println("當前客戶端的IP:"+address.getHostAddress()); } } catch (IOException e) { e.printStackTrace(); } } } class ServerThread extends Thread { // 和本線程相關的Socket Socket socket = null; public ServerThread(Socket socket) { this.socket = socket; } //線程執行的操做,響應客戶端的請求 public void run(){ InputStream is=null; InputStreamReader isr=null; BufferedReader br=null; OutputStream os=null; PrintWriter pw=null; try { //獲取輸入流,並讀取客戶端信息 is = socket.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); String info=null; while((info=br.readLine())!=null){//循環讀取客戶端的信息 System.out.println("我是服務器,客戶端說:"+info); } socket.shutdownInput();//關閉輸入流 //獲取輸出流,響應客戶端的請求 os = socket.getOutputStream(); pw = new PrintWriter(os); pw.write("歡迎您!"); pw.flush();//調用flush()方法將緩衝輸出 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //關閉資源 try { if(pw!=null) pw.close(); if(os!=null) os.close(); if(br!=null) br.close(); if(isr!=null) isr.close(); if(is!=null) is.close(); if(socket!=null) socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
/* * 客戶端 */ public class Client { public static void main(String[] args) { for(int i=0; i<100; i++){ new ClientThread(i+1).start(); } } } class ClientThread extends Thread{ private int num; ClientThread(int num){ this.num = num; } public void run(){ try { //1.建立客戶端Socket,指定服務器地址和端口 Socket socket=new Socket("127.0.0.1", 8888); //2.獲取輸出流,向服務器端發送信息 OutputStream os=socket.getOutputStream();//字節輸出流 PrintWriter pw=new PrintWriter(os);//將輸出流包裝爲打印流 pw.write("我是第" + num + "個用戶"); pw.flush(); socket.shutdownOutput();//關閉輸出流 //3.獲取輸入流,並讀取服務器端的響應信息 InputStream is=socket.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String info=null; while((info=br.readLine())!=null){ System.out.println("我是客戶端,服務器說:"+info); } //4.關閉資源 br.close(); is.close(); pw.close(); os.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }