1 package my.tomcat2; 2 3 import java.io.IOException; 4 import java.net.ServerSocket; 5 import java.net.Socket; 6 7 public class Server { 8 //服务器 9 public static ServerSocket server; 10 //关闭服务器的标志 11 private boolean isShutDown = false; 12 13 public static void main(String[] args) { 14 Server server = new Server(); 15 server.start(8888); 16 } 17 18 //运行服务器 19 public void start(int port) { 20 try { 21 server = new ServerSocket(port); 22 this.recive(); 23 } catch (IOException e) { 24 stop(); 25 } 26 } 27 28 //接受Client,客户端 29 public void recive() { 30 try { 31 while(!isShutDown){ 32 Socket client = server.accept(); 33 new Thread(new Dispatcher(client)).start(); 34 } 35 } catch (IOException e) { 36 stop(); 37 } 38 } 39 40 //停止服务器 41 public void stop() { 42 isShutDown = true; 43 CloseUtil.closeServerSocket(server); 44 } 45 }