1、首先完成一个server类,用来接收客户端的请求;代码都在一个while(true)循环中,模拟tomcat一直在启动,其中绑定一个端口,用来监听一个端口,然后创建一个输入流,获取请求的输入流,然后将输入流中的uri和参数通过request获取出来,然后通过response答应出来。

 1 package com.dongnao.mytomcat;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 import java.net.ServerSocket;
 7 import java.net.Socket;
 8 import java.text.SimpleDateFormat;
 9 import java.util.Date;
10 
11 public class Server {
12     private static int count=0;
13     public static void main(String[] args) {
14         ServerSocket ss=null;
15         Socket socket=null;
16         SimpleDateFormat  format=new SimpleDateFormat("yyy-MM-dd HH:mm:ss"); 
17         String time=format.format(new Date());
18     
19         try {
20             ss=new ServerSocket(9994);
21             System.out.println("已经连接服务器");
22         
23             while(true){
24                 socket =ss.accept();
25                 count++;
26                 System.out.println("第几次连接:"+count);
27                 
28                 InputStream is=socket.getInputStream();
29                 Request request=new Request(is);
30                 
31                 OutputStream os=socket.getOutputStream();
32                 
33                 Response response= new Response(os);
34                 
35                 
36                 
37                 //业务逻辑 ,获取静态资源;
38                 String uri=request.getUri();
39                 System.out.println(uri);
40                 //判定这个是不是静态资源
41                 if(isStaticSourse(uri)){
42                     response.writeFile(uri.substring(1));
43                 }else if(uri.endsWith(".action")){
44                     if(uri.endsWith("/login.action")){
45                         //取账户和密码
46                         LoginServlet servlet=new LoginServlet();
47                         try {
48                             servlet.service(request, response);
49                         } catch (Exception e) {
50                             e.printStackTrace();
51                         }
52                     }
53                 }    
54                 //出while循环后要关闭
55                 os.close();
56                 socket.close();
57             }
58         } catch (IOException e) {
59             e.printStackTrace();
60         }
61         
62     }
63     public static boolean isStaticSourse(String uri){
64         String[] suffixString={"html","css","js","jpg","jepg","png"};
65         boolean isStatic =false;
66         for(String suffix:suffixString){
67             if(uri.endsWith("."+suffix)){
68                 isStatic=true;
69                 break;
70             }
71         }
72         
73         return isStatic;
74     }
75 
76 }
View Code

相关文章:

  • 2021-11-29
  • 2021-06-24
  • 2021-05-28
  • 2021-05-10
  • 2021-05-06
  • 2021-11-21
猜你喜欢
  • 2022-12-23
  • 2022-01-08
  • 2022-01-08
  • 2021-11-21
  • 2022-01-03
相关资源
相似解决方案