java Socket实现简单模拟HTTP服务器

时间:2021-07-14 10:56:41

最近复习计算机网络,复习完应用层之后对于理论知识还是没有一个深刻的概念,索性就动手用Java Socket API 模拟做一个HTTP服务器,巩固一下应用层的知识。

HTTP基于TCP协议,协议采用了请求/响应模型。客户端向服务器发送一个请求,请求头包含请求的方法、URL、协议版本、以及包含请求修饰符、客户信息和内容的类似于MIME的消息结构。服务器以一个状态行作为响应,响应的内容包括消息协议的版本,成功或者错误编码加上包含服务器信息、实体元信息以及可能的实体内容——百度百科。
话不多说,还是直接上图。

java Socket实现简单模拟HTTP服务器

具体字段这里不作解释,不懂的请先自己了解http协议。这里主要是根据请求响应这一过程模拟HTTP服务器。

下面是代码:

java" id="highlighter_455333">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.example.httpserver;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
public class HttpServer {
  private static final Integer port = 80;//HTTP默认端口80
 
  public static void main(String[] args) {
    ServerSocket serverSocket;
 
    try {
      //建立服务器Socket,监听客户端请求
      serverSocket = new ServerSocket(port);
      System.out.println("Server is running on port:"+serverSocket.getLocalPort());
      //死循环不间断监听客户端请求
      while(true){
        final Socket socket = serverSocket.accept();
        System.out.println("biuld a new tcp link with client,the cient address:"+
            socket.getInetAddress()+":"+socket.getPort());
        //并发处理HTTP客户端请求
        service(socket);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 
  public static void service(Socket socket)
  {
    new Thread(){
      public void run(){
        InputStream inSocket;
        try {
          //获取HTTP请求头
          inSocket = socket.getInputStream();
          int size = inSocket.available();
          byte[] buffer = new byte[size];
          inSocket.read(buffer);
          String request = new String(buffer);
          System.out.println("ClientBrowser:\n"+request+"\n"
              + "------------------------------------------------------------------");
 
          String firstLineOfRequest = "";
          String[] heads;
          String uri = "/index.html";
          String contentType ="";
          if(request.length() > 0){
            firstLineOfRequest = request.substring(0,request.indexOf("\r\n"));
            heads = firstLineOfRequest.split(" ");
            uri = heads[1];
 
            if(uri.indexOf("html") != -1){
              contentType = "text/html";
            }else{
              contentType = "application/octet-stream";
            }
          }
          //将响应头发送给客户端
          String responseFirstLine = "HTTP/1.1 200 OK\r\n";
 
          String responseHead = "Content-Type:" + contentType +"\r\n";
 
          OutputStream outSocket = socket.getOutputStream();
          System.out.println("ServerResponse:\n"+responseFirstLine+"\n"+responseHead+"\n"
              + "--------------------------------------------------------------------");
          outSocket.write(responseFirstLine.getBytes());
          outSocket.write(responseHead.getBytes());
          //通过HTTP请求中的uri读取相应文件发送给客户端
          FileInputStream writehtml = new FileInputStream(new File("wwwroot"+uri));
          outSocket.write("\r\n".getBytes());
          byte[] htmlbuffer = new byte[writehtml.available()];
          if(writehtml !=null){
            int len = 0;
            System.out.println("writeHtml");
            while((len = writehtml.read(htmlbuffer)) != -1){
              outSocket.write(htmlbuffer, 0,len);
            }
          }
          outSocket.close();
          socket.close();
 
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }.start();
  }
 
}

代码看注释也很容易理解。现在我们在浏览器中输入服务器地址+要访问的文件

java Socket实现简单模拟HTTP服务器

在看我们控制台输出的内容:

java Socket实现简单模拟HTTP服务器

以上就是Java Socket 简单的模拟HTTP服务器全过程。希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.jianshu.com/p/2ff10a02b2b8#