zoukankan      html  css  js  c++  java
  • web服务器的原理

    web服务器的原理

    服务器webserver:

    package webserver;
    
    import java.io.*;
    import java.net.*;
    
    public class WebServer {
    
        /**
         * web服务器:实现200和404操作
         * 原理:
         * 服务器监听一个端口,并读取浏览器的请求信息,从该信息提取出访问的资源(这里为文件名)。并在工作目录下查找是否有该资源,有则输出资源内容,否则返回404
         * 测试方法:
         * 1、用String path=System.getProperty("user.dir");获取当前的工作目录,并在该目录下放要测试的文件
         * 2、访问127.0.0.1:8080/test.html
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ServerSocket server = null;
            Socket s=null;
            try
            {
                server=new ServerSocket(8180,3,InetAddress.getByName("127.0.0.1"));
            }catch(Exception e)
            {
                e.printStackTrace();
            }
            while(true)
            {
                try{
                    s=server.accept();
                    OutputStream output=s.getOutputStream();
                    InputStream input=s.getInputStream();
                    
                    //接收请求信息
                    Request request=new Request(input);
                    String filename=request.getUri();
                    //System.out.println(filename);
                    
                    //处理并响应请求信息
                    Response response=new Response(output,filename);
                    response.response();
    
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    
    }
    

    请求request:

    package webserver;
    import java.io.*;
    public class Request {
        /*
         * 接收请求的信息,并返回资源(文件名)
         * */
        InputStream input;
        public Request(InputStream input)
        {
            this.input=input;
        }
        public String getUri() throws IOException
        {
            String content=null,str=null;
            StringBuffer request = new StringBuffer();  
            byte[] buffer = new byte[2048];  
            int i = 0;  
              
            try {  
                i = input.read(buffer);  //读取内容并存入buffer数组中,并返回读取的的字节数。
            } catch (IOException e) {  
                e.printStackTrace();  
                i = -1;  
            }  
            //将buffer数组转换为字符串
            for(int k = 0; k < i; k++) {  
                request.append((char)buffer[k]);  
            }  
            content=request.toString();
        /*    
         *以下方法错误!用该返回会使浏览器不断处于请求连接状态
         * BufferedReader br=new BufferedReader(new InputStreamReader(input));
            while((str=br.readLine())!=null)
            {
                content=content+str+"
    ";
            }
        */    
            if(content!=null)
                return getFilename(content);
            else return null;
        }
        /*提取文件名*/
        public String getFilename(String content)
        {
            int a,b;
            a=content.indexOf(' ');
            if(a!=-1)
            {
                b=content.indexOf('?',a+1);
                if(b==-1)b=content.indexOf(' ',a+1);
                return content.substring(a+2,b);
            }
            return null;
        }
    }
    

    响应response:

    package webserver;
    
    import java.io.*;
    import java.io.File;
    import java.io.IOException;
    import java.io.OutputStream;
    
    public class Response {
        /**
         * 响应并处理请求信息
         */
        public OutputStream output;
        public String filename;
         private static final int BUFFER_SIZE = 1024; 
        public  Response(OutputStream output,String filename)
        {
            this.output=output;
            this.filename=filename;
        }
        public void response() throws IOException
        {
            String path=System.getProperty("user.dir");//获取当前的工作目录
            byte[] buffer = new byte[BUFFER_SIZE];  
            int ch;  
            FileInputStream fis = null;  
            //System.out.println(path+File.separator+filename);
            if(path!=null&&filename!=null)
            {
                File file=new File(path,filename);
                String str="";
                /*必须添加响应头,否则无法以html格式显示内容*/
                if(file.exists())
                {
                    fis = new FileInputStream(file);  
                    str = "HTTP/1.1 200 OK 
    " +  
                     "Content-Type: text/html
    " +  
                     "
    " ;
                    output.write(str.getBytes());
                    ch = fis.read(buffer);                
                    while(ch != -1) {  
                        output.write(buffer, 0, ch);  
                        ch = fis.read(buffer, 0, BUFFER_SIZE);  
                    }  
                }
                else
                {
                     str = "HTTP/1.1 404 File Not Found 
    " +  
                     "Content-Type: text/html
    " +  
                     "Content-Length: 100
    " +  
                     "
    " +  
                     "<h1>404 File Not Found!</h1>"; 
                    output.write(str.getBytes());
                }
            }
            output.close();
        }
    }
    

    遇到的问题

    运行时一直遇到nullpointerexception,更改端口后能响应请求。以从学校网站下载的html为例,通过浏览器访问8180端口,下的test.html会响应相应的页面,但是当访问不存在的页面时,浏览器会一直处于加载状态。
    未提示404错误信息。

    参考链接

    https://www.cnblogs.com/yingww/p/4097620.html

  • 相关阅读:
    屠呦呦团队研究新进展:青蒿中有其他抗疟成分
    lammps模拟化学反应(1)
    伪类的使用--鼠标悬浮效果
    bootstrap中模态框的使用
    idea_2018.1.5版本的激活使用
    火狐浏览器开发者版本
    使用bootstrap的相关配置
    StringBuffer类
    如何判断字符串中大写字母,小写字母和数字出现的次数??
    ssm框架结构的搭建
  • 原文地址:https://www.cnblogs.com/HuppertWu/p/10534226.html
Copyright © 2011-2022 走看看