首页 > Web开发 > 详细

web服务器的原理

时间:2019-03-15 11:19:50      阅读:156      评论:0      收藏:0      [点我收藏+]

代码如下:

1、WebServer.java文件

技术分享图片
 1 package webserver;
 2 
 3 import java.io.*;
 4 import java.net.*;
 5 
 6 public class WebServer {
 7 
 8     /**
 9      * web服务器:实现200和404操作
10      * 原理:
11      * 服务器监听一个端口,并读取浏览器的请求信息,从该信息提取出访问的资源(这里为文件名)。并在工作目录下查找是否有该资源,有则输出资源内容,否则返回404
12      * 测试方法:
13      * 1、用String path=System.getProperty("user.dir");获取当前的工作目录,并在该目录下放要测试的文件
14      * 2、访问127.0.0.1:8080/test.html
15      */
16     public static void main(String[] args) {
17         // TODO Auto-generated method stub
18         ServerSocket server = null;
19         Socket s=null;
20         try
21         {
22             server=new ServerSocket(8080,3,InetAddress.getByName("127.0.0.1"));
23         }catch(Exception e)
24         {
25             e.printStackTrace();
26         }
27         while(true)
28         {
29             try{
30                 s=server.accept();
31                 OutputStream output=s.getOutputStream();
32                 InputStream input=s.getInputStream();
33                 
34                 //接收请求信息
35                 Request request=new Request(input);
36                 String filename=request.getUri();
37                 //System.out.println(filename);
38                 
39                 //处理并响应请求信息
40                 Response response=new Response(output,filename);
41                 response.response();
42 
43             }catch(Exception e)
44             {
45                 e.printStackTrace();
46             }
47         }
48     }
49 
50 }
技术分享图片

2、Request.java

技术分享图片
 1 package webserver;
 2 import java.io.*;
 3 public class Request {
 4     /*
 5      * 接收请求的信息,并返回资源(文件名)
 6      * */
 7     InputStream input;
 8     public Request(InputStream input)
 9     {
10         this.input=input;
11     }
12     public String getUri() throws IOException
13     {
14         String content=null,str=null;
15         StringBuffer request = new StringBuffer();  
16         byte[] buffer = new byte[2048];  
17         int i = 0;  
18           
19         try {  
20             i = input.read(buffer);  //读取内容并存入buffer数组中,并返回读取的的字节数。
21         } catch (IOException e) {  
22             e.printStackTrace();  
23             i = -1;  
24         }  
25         //将buffer数组转换为字符串
26         for(int k = 0; k < i; k++) {  
27             request.append((char)buffer[k]);  
28         }  
29         content=request.toString();
30     /*    
31      *以下方法错误!用该返回会使浏览器不断处于请求连接状态
32      * BufferedReader br=new BufferedReader(new InputStreamReader(input));
33         while((str=br.readLine())!=null)
34         {
35             content=content+str+"\r\n";
36         }
37     */    
38         if(content!=null)
39             return getFilename(content);
40         else return null;
41     }
42     /*提取文件名*/
43     public String getFilename(String content)
44     {
45         int a,b;
46         a=content.indexOf(‘ ‘);
47         if(a!=-1)
48         {
49             b=content.indexOf(‘?‘,a+1);
50             if(b==-1)b=content.indexOf(‘ ‘,a+1);
51             return content.substring(a+2,b);
52         }
53         return null;
54     }
55 }
技术分享图片

3、Response.java

技术分享图片
 1 package webserver;
 2 
 3 import java.io.*;
 4 import java.io.File;
 5 import java.io.IOException;
 6 import java.io.OutputStream;
 7 
 8 public class Response {
 9     /**
10      * 响应并处理请求信息
11      */
12     public OutputStream output;
13     public String filename;
14      private static final int BUFFER_SIZE = 1024; 
15     public  Response(OutputStream output,String filename)
16     {
17         this.output=output;
18         this.filename=filename;
19     }
20     public void response() throws IOException
21     {
22         String path=System.getProperty("user.dir");//获取当前的工作目录
23         byte[] buffer = new byte[BUFFER_SIZE];  
24         int ch;  
25         FileInputStream fis = null;  
26         //System.out.println(path+File.separator+filename);
27         if(path!=null&&filename!=null)
28         {
29             File file=new File(path,filename);
30             String str="";
31             /*必须添加响应头,否则无法以html格式显示内容*/
32             if(file.exists())
33             {
34                 fis = new FileInputStream(file);  
35                 str = "HTTP/1.1 200 OK \r\n" +  
36                  "Content-Type: text/html\r\n" +  
37                  "\r\n" ;
38                 output.write(str.getBytes());
39                 ch = fis.read(buffer);                
40                 while(ch != -1) {  
41                     output.write(buffer, 0, ch);  
42                     ch = fis.read(buffer, 0, BUFFER_SIZE);  
43                 }  
44             }
45             else
46             {
47                  str = "HTTP/1.1 404 File Not Found \r\n" +  
48                  "Content-Type: text/html\r\n" +  
49                  "Content-Length: 100\r\n" +  
50                  "\r\n" +  
51                  "<h1>404 File Not Found!</h1>"; 
52                 output.write(str.getBytes());
53             }
54         }
55         output.close();
56     }
57 }
技术分享图片

在浏览器进行验证:

技术分享图片

 

 技术分享图片

服务器原理分析:

  在此处Java的服务器中是使用套接字(Socket)来识别客户端(浏览器打开服务器的8080端口)进行客户端和服务器的交互.

大体原理(具体原理是利用网络的七层协议):

    浏览器客户键入网址(http协议+服务器ip+服务器端口号+访问的文件位置+......)

    --->浏览器根据ip找到目的主机

    -->根据端口号找到目的主机上的目的服务器

    -->根据访问的文件位置信息找到相应文件

    -->执行该文件

 

 

 

 

web服务器的原理

原文:https://www.cnblogs.com/YuanXiaolong/p/10535806.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!