简单认识HTTP协议

来源:互联网 发布:兄弟连it 编辑:程序博客网 时间:2024/05/16 10:09

简单认识HTTP协议

技术:通过Socket和多线程技术,实现一个Java Web服务器,加深对http协议的认识。

首先创建一个类 WebServer,此类的监听80端口,代码如下:

package com.v512;
import java.net.ServerSocket;
import java.net.Socket;

public class WebServer {

/** * 通过监听某一端口,来实现浏览器和程序的交互 * @param port * @throws Exception */public void startServer(int port) throws Exception {    ServerSocket serverSocket = new ServerSocket(port);    while (true) {        //socket通信        Socket socket = serverSocket.accept();        new Processor(socket).start();    }}public static void main(String[] args) throws Exception {    int port = 80;    if (args != null && args.length > 0) {        port = Integer.parseInt(args[0]);    }    new WebServer().startServer(port);}

}

通过上面一个类可以知道,此类监听80端口,通过socket通信,并调用Processor这个类来具体实现。

下面是Processor这个类的具体实现:

package com.v512;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {

private Socket socket;private InputStream in;private PrintStream out;//哪个目录下的文件可以被访问public static final String WEB_ROOT = "";public Processor(Socket socket) {    this.socket = socket;    try {        in = socket.getInputStream();        out = new PrintStream(socket.getOutputStream());    } catch (IOException e) {        e.printStackTrace();    }}@Overridepublic void run() {    //先通过请求,拿到要访问的文件    String fileName = parse(in);    //拿到该文件之后,返回到浏览器    sendFile(fileName);}/** * 将拿到的文件返回浏览器 * http协议返回的数据类型    *                  http/1.0(http版本) 200(状态码) sendFile(消息)(第三个是个人浅见) *                  content-length:1111111  (字段长度)(具体参考http头部消息) *                  \n                       换行符 * 具体的http协议 返回三行数据 * @param fileName */private void sendFile(String fileName) {    //只让访问特定目录下的文件    File file = new File(WEB_ROOT + fileName);    if (!file.exists()) {        //常见的404错误        sendErrorMessage(404, "file not found");        return;    }    try {        byte[] content = new byte[fileName.length()];        InputStream in = new FileInputStream(file);        in.read(content);        out.println("HTTP/1.0 200 sendFile");        out.println("content-length:" + content.length);        out.println();        out.write(content);        out.flush();        out.close();        in.close();    } catch (Exception e) {        e.printStackTrace();    }}/** * 通过http协议,获取文件名 * @param in * @return */public String parse(InputStream in) {    String fileName = null;    BufferedReader br = new BufferedReader(new InputStreamReader(in));    try {        //获取第一行数据        String httpMessage = br.readLine();        String[] content = httpMessage.split(" ");        if (content.length != 3) {            sendErrorMessage(400, "Client query error");            return null;        }        System.out.println("code:" + content[0] + ",fileName:" + content[1]                + ",http version:" + content[1]);        fileName = content[1];    } catch (IOException e) {        e.printStackTrace();    }    return fileName;}/** * 处理错误的统一方法 * @param code * @param errorMessage */private void sendErrorMessage(int code, String errorMessage) {    out.println("HTTP/1.0 " + code + " " + errorMessage);    out.println("content-type:text/html");    out.println();    out.println("<html>");    out.println("<head>");    out.println("<title>Error");    out.println("</title>");    out.println("</head>");    out.println("<body>");    out.println("<h1>ErrorCode:" + code + ",ErrorMessage:" + errorMessage);    out.println("</h1>");    out.println("</body>");    out.println("<html>");    out.flush();    out.close();    try {        in.close();    } catch (IOException e) {    }}

}

通过Processor这个类,可以发现,当浏览器访问服务器某一个文件的时候,是需要先通过获取这个文件名,然后去查找这个文件,如果存在,就返回 http协议 + 文件内容,如果不存在,返回 404错误代码。

通过这两个类的学习,可以基本了解 http协议,以及前后台如何交互的知识,对Servlet的起源也有一定的帮助。

本博客内容:是学习了 v512工作室的视频得到的,加上一些自己的感悟,如果需要视频的话,私信找我。

原创粉丝点击