JAVA实现简单的HTTP服务器

        用JAVA实现简单的HTTP服务器

        实现不难,但也要全面掌握JAVA基础编程,还需要了解HTTP协议,和HTTP服务器/客户端的基本工作原理。

        HTTP是一个基于请求/响应模式的、无状态的协议。客户端(浏览器) 与服务器端(Web服务器应用程序)建立连接后,向服务器发出

一个请求,服务器对这个请求进行处理,然后返回一个响应信息,之后双方的连接被关闭。

        这里,我们要实现的也就是我们得到“浏览器”的请求后,响应"GET"命令的过程。我们先来看看HTTP协议中"GET”命令的格式:
                                GET Request-URI HTTP/1.1   //注意命令行中的空格不能少
        当我们通过浏览器的地址栏中直接输入网址的方式去访问网页的时候,浏览器采用的就是GET方法向服务器端请求获取资源。

        下面就是代码:

HttpServer类,也就是启动服务器的main()方法所在类:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

public class HttpServer {


         public static void main(String[] args) {
 
                 try {
               
//为了方便程序的通用性,我们定义Properties属性文件来配置Web服务器的跟目录
                                Properties pro = new Properties();
                                File f = new File("d:\\Properties.txt");    //属性配置文件放D盘跟目录
                                InputStream ins = new FileInputStream(f);
                                ServerSocket ss = new ServerSocket(80); //对端口80监听
                                pro.load(ins);    
//读入属性文件
   
                                String ph = pro.getProperty("path");  
//得到path属性值
                                System.out.println(ph);
               //循环监听   当得到一个客户端Socket后 建立并启动会话线程
                                while(true)
                                      {
                                              Socket sk = ss.accept();
                                              Session se = new Session(sk,ph);
                                              Thread thread = new Thread(se);
                                              thread.start();
                                      }
                       } catch (IOException e) {
  
                                    e.printStackTrace();
                                   }
            }
}

 

Session类,继承Runnable接口,方便实现服务器端支持多用户(多线程),run()方法内实现对GET命令的处理和响应:

import java.io.*;
import java.net.Socket;
import java.util.*;

public class Session implements Runnable {
          private Socket sk;
          private String PATH;
          public static final int MAX_LENGHT = 1024;
   //构造器, 传递进来Socket 和web文件的跟目录
         public Session(Socket sk, String path) {
                              this.sk = sk;
                              this.PATH = path;
                       }

          public void run() {

                try {
                        BufferedReader br =
                                new BufferedReader(new InputStreamReader(sk.getInputStream()));
                        OutputStream out = sk.getOutputStream();
                      //br 封装了服务器端的输入流 用来读入客户端发来的请求行s
                        String s = br.readLine();
                        while (s != null) {
                                   System.out.println("客户端指令:" + s);
                                    if (s.length() < 3)  break;
                                   //取"GET"命令
                                    String cmd = s.substring(0, 3);
                                    if (cmd.equalsIgnoreCase("GET")) {
                                             //取要获得的文件名
                                            String filename = s.substring(5, s.lastIndexOf(" "));
                                            
//filePath为文件绝对路径
                                            String filePath = PATH + filename;
                                            System.out.println(filePath);
                                            //读入文件到buf数组
                                            File file = new File(filePath);
                                                       if (!file.exists()) {
                                                       filename = "index.html";
                                                       file = new File(PATH + filename);
                                                          }
                                            InputStream in = new FileInputStream(file);
                                            byte[] buf = new byte[MAX_LENGHT];
                                            //写入文件到客户端
                                            int n = 0;
                                            while ((n = in.read(buf)) != -1) {
                                                     out.write(buf, 0, n);
                                                     out.flush();

                                           }
                                 in.close();

                                 }
                           s = br.readLine();

                       }
                      out.close();
                      sk.close();

  } catch (IOException e) {
   e.printStackTrace();
  }

 }

}

提供源码的下载  如果要测试的话记得一定要在 D盘跟目录下建立名为:“Properties.txt”的属性配置文件,并在里面编写健值对:path=你的本地web站点跟目录  。然后编译-->运行,打开IE浏览器 在地址栏输入:http://localhost:80/index.html  (端口可以任意配置,但要和ServerSocket监听的端口一致)。


 将下载下来的.txt 后缀名改为.rar 在解压  (没办法,不支持RAR)

你可能感兴趣的:(HTTP服务器)