多线程静态Web服务器开发小试(java)

克服内存溢出问题采用缓冲式输出

文件一:

package com.cn.lcl;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
public class HttpWebServerOfLcl {
    private static int counter = 0;
    public static void main(String[] args{
        WebServer();
    }
    public static void WebServer() {
        int PORT = 8080;
        ServerSocket server = null;
        Socket client = null;
        try {
            server = new ServerSocket(PORT);
            System.out.println("WEB服务器启动,访问端口号为:" + PORT);
            while (true) {
                client = server.accept();
                counter++;
                System.out.println("第" + counter + "个客户请求");
                new CommunicationThread(client).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


class CommunicationThread extends Thread {
    Socket client = null;
    public CommunicationThread(Socket client{
        this.client = client;
    }
    public void run() {
        try {
            String destIp = client.getInetAddress().toString();
            String destPort = client.getPort() + "";
            System.out.println("请求来源IP为:" + destIp + "----请求响应端口为:" + destPort);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                        client.getInputStream()));
            String inputLine = reader.readLine();
            System.out.println("inputLine为:" + inputLine);
            String resourceUrl = inputLine.substring(inputLine.indexOf('/') +
                    1, inputLine.lastIndexOf('/') - 5);
            int i = 0;
            while ((inputLine = reader.readLine()) != null) {
                if (inputLine.equals("")) {
                    break;
                }
                i++;
                System.out.println("第" + i + "行http头部信息为: " + inputLine);
            }
            resourceUrl = URLDecoder.decode(resourceUrl, "UTF-8");
            System.out.println("请求资源为:" + resourceUrl);
            File file = new File(resourceUrl);
            PrintStream outstream = new PrintStream(client.getOutputStream());
            if (file.exists() && !file.isDirectory()) {
                System.out.println("文件存在");
                outstream.println("HTTP/1.0 200 OK");
                outstream.println("MIME_version:1.0");
                outstream.println("Content_Type:text/html");
                outstream.println("Content_Length:" + file.length());
                outstream.println("");
                transportFile(outstream, file);
                outstream.flush();
            } else {
                String notFound = "<html><head><title>Not Found</title></head><body><h1>404 file not found</h1></body></html>";
                outstream.println("HTTP/1.0 404 no found");
                outstream.println("Content_Type:text/html");
                outstream.println("Content_Length:" + notFound.length() + 2);
                outstream.println("");
                outstream.println(notFound);
                outstream.flush();
            }
            // outstream.close();
            long b = 1;
            while (b < 3600000) {
                b++;
            }
            reader.close();
            client.close();
        } catch (Exception e) {
            //System.out.println("run方法内出错:" + e.getMessage());
        } finally {
            /*
             * try { //client.close(); System.out.println("本次请求成功关闭!"); } catch
             * (IOException e) { e.printStackTrace(); }
             */

        }
    }

    public void transportFile(PrintStream ps, File file{
        try {
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            byte[] temp = new byte[10240];
            int a = 0;
            while ((a = in.read(temp, 010240)) != -1) {
                ps.write(temp);
                ps.flush();
            }
            in.close();
        } catch (IOException e) {
            System.out.println("文件传输中出错,错误信息为:" + e.getMessage());
        } finally {
            ps.close();
            System.out.println("传输完毕");
        }
    }
}

文件二:index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head> 
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  <title>我的JAVA WEB服务器</title> 
 </head> 
 <body> 
  <center> 
   <h1> Hello ,DaXiongJie!This is WuYou ! </h1> 
   <h1> 祝愿2017年 </h1> 
   <hr /> 
   <form action="/index.html"> 
    <img alt="" src="test.jpg" /> 
    <br /> 
    <br /> 
    <br /> 
    <video width="800" height="600" controls="controls"> 
     <source src="半妖倾城.mp4" type="video/mp4"></source> 您的浏览器不支持此种视频格式。 
    </video> 
   </form> 
  </center>   
 </body>
</html>
原文地址:https://www.cnblogs.com/skycodefamily/p/5683105.html