1 package coreBookSocket; 2 3 import java.io.IOException; 4 import java.net.ServerSocket; 5 import java.net.Socket; 6 7 /* 8 * 這個方法的主要目地是為了用多線程的方法實現網絡編程,讓多個客戶端可以同時連接到一個服務器 9 *1:准備工作和單個客戶端編程類似,先建立服務器端的套接字,同時讓服務器那邊調用accept()方法來接受服務器端的信息,並且返回一個Socket客戶端套接字 10 *2:這里面定一個while循環主要是為了讓多線程能夠一直持續的進行下去,為此while循環開始執行的時候都會先建立 11 * 一個新的線程來處理服務器和客戶端之間的連接 12 *3:同時定一個threadedEchoHandler來實現Runnable接口,而該類的主要作用是為了實現客戶端循環通信的demo 13 * author:by XIA 14 * data:9.26.2016 15 */ 16 public class SimpleServerOfClients { 17 public static void main(String[] args) throws IOException { 18 19 int i=1; 20 ServerSocket server=new ServerSocket(8189); 21 while(true) 22 { 23 Socket client=server.accept(); 24 System.out.println("Spawning "+i); 25 Runnable r = new threadedEchoHandler(client); 26 Thread t=new Thread(r); 27 t.start(); 28 i++; 29 } 30 } 31 }
package coreBookSocket; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; public class threadedEchoHandler implements Runnable { private Socket client; public threadedEchoHandler(Socket i) { client=i; } @Override public void run() { try { InputStream ins=client.getInputStream(); OutputStream outs=client.getOutputStream(); Scanner in=new Scanner(ins); PrintWriter out=new PrintWriter(outs, true); System.out.println("Hello! Enter bye to exit!"); boolean done=false; while(!done&&in.hasNextLine()) { String line = in.nextLine(); System.out.println("回應:" + line); if (line.trim().equalsIgnoreCase("bye")) { done=true; } } client.close(); } catch (IOException e) { e.printStackTrace(); } } }