自己动手写http服务器---java版

 

 

大概介绍一下原理吧,浏览器打开网页可以简单分为3个阶段:

1.通过socket向服务器发送一个符合一定格式的请求字符串(里面包含了用户输入的网址),比如:

Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Connection keep-alive
Host localhost:8001
User-Agent Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0

 

2.服务器收到浏览器的请求字符串,解析出用户所请求的网址,网址其实对应服务器中的文件。
   例如 http:\\www.demo.com其实对应服务器里的 http:\\www.demo.com\index.html,服务器会将index.html这个文件读取到byte数组中,并加上头信息(也是字符串),返回给发送请求的浏览器。


3.浏览器接收到服务器返回的字节流,根据返回的头信息,判断返回的byte数组原始的数据类型(网页、图片、其他),例如返回的头信息如下:
  Content-Type text/html

说明返回的byte数组原来是html页面,浏览器会解析html页面,显示数据。
如果服务器返回的头信息如下:
Content-Type image/jpeg
说明返回的byte数组原来是图片,浏览器会将byte数组存储为图片,显示图片。


下面给出源码:
注:1.要运行程序,需要在同目录下新建webapp文件夹,将想运行的网站放入(暂时只支持html,jpg,gif,png)
2.程序运行参数:可以无参数运行,默认绑定80端口,有可能会冲突。可添加一个参数设定端口,例如:java -jar MyHtmlServer.jar 8001
8001为绑定的端口号。
3.运行程序后,在浏览器中输入 http://localhost:端口号/资源路径即可。例如绑定的是8001端口,在webapp文件夹下有index.html文件,现在需要访问这个文件,在浏览器中输入:http://localhost:8001/index.html 即可访问。如果绑定的是80端口,可直接写:http://localhost/index.html,浏览器默认使用80作为服务器端口。
源码:
[java] view plaincopyprint?import java.io.BufferedReader; 
import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.InterruptedIOException; 
import java.io.OutputStream; 
import java.net.ServerSocket; 
import java.net.Socket; 
 
public class MyHtmlServer { 
     
    public static void main(String[] args) throws IOException { 
        int port=80; 
        if(args.length>0) 
            port=Integer.valueOf(args[0]); 
        new MyHtmlServer().start(port); 
 
    } 
     
    /**
     * 在指定端口启动http服务器
     * @param port 指定的端口
     * @throws IOException
     */ 
    public void start(int port) throws IOException { 
        ServerSocket server = new ServerSocket(port); 
        System.out.println("server start at "+port+"..........."); 
        while (true) { 
            Socket client = server.accept(); 
            ServerThread serverthread = new ServerThread(client); 
            serverthread.start(); 
 
        } 
    } 
 
    /**
     * 服务器响应线程,每收到一次浏览器的请求就会启动一个ServerThread线程
     * @author 
     *
     */ 
    class ServerThread extends Thread { 
        Socket client; 
 
        public ServerThread(Socket client) { 
            this.client = client; 
        } 
         
        /**
         * 读取文件内容,转化为byte数组
         * @param filename 文件名
         * @return
         * @throws IOException
         */ 
        public  byte[] getFileByte(String filename) throws IOException 
        { 
            ByteArrayOutputStream baos=new ByteArrayOutputStream(); 
            File file=new File(filename); 
            FileInputStream fis=new FileInputStream(file); 
            byte[] b=new byte[1000]; 
            int read; 
            while((read=fis.read(b))!=-1) 
            { 
                baos.write(b,0,read); 
            } 
            fis.close(); 
            baos.close(); 
            return baos.toByteArray(); 
        } 
 
         
        /**
         * 分析http请求中的url,分析用户请求的资源,并将请求url规范化
         * 例如请求 "/"要规范成"/index.html","/index"要规范成"/index.html"
         * @param queryurl 用户原始的url
         * @return 规范化的url,即为用户请求资源的路径
         */ 
        private String getQueryResource(String queryurl) 
        { 
            String queryresource=null; 
            int index=queryurl.indexOf('?'); 
            if(index!=-1) 
            { 
                queryresource=queryurl.substring(0,queryurl.indexOf('?')); 
            } 
            else 
                queryresource=queryurl; 
             
            index=queryresource.lastIndexOf("/"); 
            if(index+1==queryresource.length()) 
            { 
                queryresource=queryresource+"index.html"; 
            } 
            else 
            { 
                String filename=queryresource.substring(index+1); 
                if(!filename.contains(".")) 
                    queryresource=queryresource+".html"; 
            }            
            return queryresource; 
 
        } 
         
     
        /**
         * 根据用户请求的资源类型,设定http响应头的信息,主要是判断用户请求的文件类型(html、jpg...)
         * @param queryresource
         * @return
         */ 
        private String getHead(String queryresource) 
        { 
            String filename=""; 
            int index=queryresource.lastIndexOf("/"); 
            filename=queryresource.substring(index+1); 
            String[] filetypes=filename.split("\\."); 
            String filetype=filetypes[filetypes.length-1]; 
            if(filetype.equals("html")) 
            { 
                return "HTTP/1.0200OK\n"+"Content-Type:text/html\n" + "Server:myserver\n" + "\n"; 
            } 
            else if(filetype.equals("jpg")||filetype.equals("gif")||filetype.equals("png")) 
            { 
                return "HTTP/1.0200OK\n"+"Content-Type:image/jpeg\n" + "Server:myserver\n" + "\n"; 
            } 
            else return null; 
             
        } 
 
        @Override 
        public void run() { 
            InputStream is; 
            try { 
                is = client.getInputStream(); 
                BufferedReader br = new BufferedReader( 
                        new InputStreamReader(is)); 
                int readint; 
                char c; 
                byte[] buf = new byte[1000]; 
                OutputStream os = client.getOutputStream(); 
                client.setSoTimeout(50); 
                byte[] data = null; 
                String cmd = ""; 
                String queryurl = ""; 
                int state = 0; 
                String queryresource; 
                String head; 
                while (true) { 
                    readint = is.read(); 
                    c = (char) readint; 
                    boolean space=Character.isWhitespace(readint); 
                    switch (state) { 
                    case 0: 
                        if (space) 
                            continue; 
                        state = 1; 
                    case 1: 
                        if (space) { 
                            state=2; 
                            continue; 
                        } 
                        cmd+=c; 
                        continue; 
                    case 2: 
                        if(space) 
                            continue; 
                        state=3; 
                    case 3: 
                        if(space) 
                            break; 
                        queryurl+=c; 
                        continue; 
                    } 
                    break; 
                } 
 
                queryresource=getQueryResource(queryurl); 
                head=getHead(queryresource); 
 
                while (true) { 
                    try { 
                        if ((readint = is.read(buf)) > 0) { 
                        //  System.out.write(buf);  
                        } else if (readint < 0) 
                            break; 
                    } catch (InterruptedIOException e) { 
                        data = getFileByte("webapp"+queryresource); 
                    } 
 
                    if (data != null) { 
                        os.write(head.getBytes("utf-8")); 
                        os.write(data); 
                        os.close(); 
                        break; 
                    } 
                } 
            } catch (IOException e) { 
                // TODO Auto-generated catch block  
                e.printStackTrace(); 
            } 
 
        } 
    } 
     
     
         
     
     
     
 
     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值