`
Ydoing
  • 浏览: 101106 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

简单HTTP服务器的Java实现

 
阅读更多

在web的最初阶段是不支持web服务器与用户的交互的.也就是说web服务器不能动态的生成用户要访问的页面,web服务器提供给用户的页面都是提前生成好的.所以也说这种页面是静态页面.
比如说用户请求访问http://localhost:8088/hello1.htm, 那么web服务器从自己的想要目录下获取hello1.htm(已经存在).然后通过HTTP协议返回给用户.

下面我们来模拟一下这个过程.因为HTTP协议是应用层协议,基于TCP,所以我们用Java的socket来编写HTTP服务器.

编写HttpServer

import java.io.*;
import java.net.*;

public class HttpServer {
    private static final int port = 8088;
    private ServerSocket serverSocket = null;

    public HttpServer() throws IOException {
        serverSocket = new ServerSocket(port);
        System.out.println("HTTPServer startup OK...");
    }

    public String getRequest(Socket socket) throws IOException {
        InputStream socketIn = socket.getInputStream();
        int size = socketIn.available();
        byte[] requestBuff = new byte[size];
        socketIn.read(requestBuff);
        return new String(requestBuff);
    }

    public String getURI(String request) {
        String firstLine = request.substring(0, request.indexOf("\r\n"));
        String[] parts = firstLine.split(" ");

        return parts[1];
    }

    public String getContentType(String URI) {
        /* 决定HTTP响应正文的类型 */
        String contentType;
        if (URI.indexOf("html") != -1 || URI.indexOf("htm") != -1)
            contentType = "text/html";
        else if (URI.indexOf("jpg") != -1 || URI.indexOf("jpeg") != -1)
            contentType = "image/jpeg";
        else if (URI.indexOf("gif") != -1)
            contentType = "image/gif";
        else
            contentType = "application/octet-stream";
        return contentType;
    }

    public InputStream getResponseContent(String URI)
            throws FileNotFoundException {
        InputStream htmlInputStream = new FileInputStream(
                System.getProperty("user.dir") + "/WebRoot" + URI);
        return htmlInputStream;
    }

    public String assembleResponseHead(String URI, String contentType) {
        /* 创建HTTP响应结果 */
        // HTTP响应的第一行
        String responseFirstLine = "HTTP/1.1 200 OK\r\n";
        // HTTP响应头
        String responseHeader = "Content-Type:" + contentType + "\r\n\r\n";

        return responseFirstLine + responseHeader;
    }

    public void service() throws InterruptedException {
        while (true) {
            Socket socket;
            try {
                socket = serverSocket.accept();

                String request = getRequest(socket);
                System.out.println("HttpServer receive request:\n" + request);

                String URI = getURI(request);

                String contentType = getContentType(URI);
                OutputStream out = socket.getOutputStream();

                out.write(assembleResponseHead(URI, contentType).getBytes());

                int len = 0;
                byte[] buffer = new byte[128];
                InputStream htmlInputStream = getResponseContent(URI);
                while ((len = htmlInputStream.read(buffer)) != -1)
                    out.write(buffer, 0, len);
                Thread.sleep(1000);
                socket.close(); // 关闭TCP连接
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) throws IOException,
            InterruptedException {
        HttpServer httpServer = new HttpServer();
        // System.out.println(System.getProperty("user.dir"));
        httpServer.service();
    }

}

创建hello1.htm

然后在项目的目录/WebRoot下放置一个hello1.htm页面:
这里写图片描述
hello1.htm很简单,显示标题HelloWorld

<html>
<head>
<title>HelloWorld</title>
</head>
<body >
  <h1>Hello</h1>
</body>
</html>

访问hello1.htm

启动HTTPServer,在浏览器访问http://localhost:8088/hello1.htm,看到eclipse的Console输出

GET /hello1.htm HTTP/1.1
Host: localhost:8088
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.125 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4

这是浏览器请求的HTTP消息,包括了HTTP头,请求方式,有时也有请求正文(这里没有).
浏览器显示为:

这里写图片描述
这样简单的HTTPSever就算完成了,后续我将继续研究模拟一下Servlet的HTTP服务器.

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>

版权声明:本文为博主原创文章,未经博主允许不得转载。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics