Java使用TCP实现Web文件下载页面


# 说明

本程序基于Java开发,可以根据您设置的IP和端口号,帮您创建一个简易的Web网站
1.您可以在webroot/config/config.properties文件中修改IP、端口、网站标题等配置。
2.您可以将文件存到webroot文件夹下,然后重启程序,生成新的webroot/index.html文件
3.您可以在启动程序后,通过[IP:端口]的形式访问这个主页,例如在浏览器里输入127.0.0.1:8080
4.关于启动程序,需要您已配置好Java环境,然后有两种方法
4.1 在命令行输入java -jar Zxy97Server.jar
4.2 直接单击作者提供的start.bat批处理文件。
提示:
1.您需要配置好java环境,并在保证当前目录下的lib文件夹下存在javax.servlet.jar
1.如果端口号为80,可以省略[:端口],例如在浏览器里输入127.0.0.1
2.每次向webroot文件夹下添加文件后请重启本程序
3.退出控制台程序请按Ctrl+C或者Ctrl+Z
4.作者主页:http://zxy97.com
5.直接使用请下载软件包:http://s.zxy97.com/soft_1
或者获取软件包和源代码 https://download.csdn.net/download/zhaoxuyang1997/10606904
6.详细的使用说明请访问我的QQ空间日志:https://user.qzone.qq.com/1395359719/blog/1536576700

com.zxy97.server.Httpserver.java

package com.zxy97.server;

import com.zxy97.server.file.Config;
import com.zxy97.server.file.Create;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @名称 Java使用TCP实现Web文件下载页面
 * @作者 zhaoxuyang1997
 * @时间 2018-09-10 17:37
 * @版本 V1.0
 */
public class HttpServer {
    com.zxy97.server.file.Config config = new com.zxy97.server.file.Config();
    
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    private final boolean shutdown = false;
    public static void main(String[] args){
        Create.createHtml();
        HttpServer server = new HttpServer();
        server.await();
    }
    public void await(){
        System.out.println("服务端正在等待客户端请求……");
        ServerSocket serverSocket = null;
        int port = Integer.valueOf(config.getPort());
        try{
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName(config.getIP()));
            System.out.printf("IP=%s\n",config.getIP());
            System.out.printf("端口号=%d\n",port);
            System.out.printf("如果需要修改配置,请访问配置文件[%s]\n",Config.CONFIG_FILE);
            System.out.println("作者主页:http://zxy97.com");
            if(port==80){
                System.out.printf("通过在浏览器中输入[http://%s]即可访问[%s]下的文件(每次添加文件后请重启本程序)\n",config.getIP(),Config.WEB_ROOT);
            }else{
                System.out.printf("通过在浏览器中输入[http://%s:%d]即可访问[%s]下的文件(每次添加文件后请重启本程序)\n",config.getIP(),port,Config.WEB_ROOT);
            }
            System.out.println("程序正在运行中……");
        }catch(IOException e){
            System.exit(1);
        }
        while(!shutdown){
            Socket socket;
            InputStream input;
            OutputStream output;
            try{
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();
                
                Request request = new Request(input);
                Response response = new Response(output);
                
                request.parse();
                response.setRequest(request);
                response.sendStaticResource();
     
                socket.close();
            }catch(IOException e){
                System.out.println("响应客户端出现了错误!");
                continue;
            }     
        }
    }
}


com.zxy97.server.Request.java

package com.zxy97.server;

import com.zxy97.server.file.Config;
import java.io.IOException;
import java.io.InputStream;

/**
 * @作者 zhaoxuyang1997
 * @时间 2018-07-20 04:04
 * @版本 V1.0
 */
public class Request {
    private final InputStream input;
    private String uri;
    
    public Request(InputStream input){
        this.input = input;
    }
    public void parse(){
        StringBuffer request;
        request = new StringBuffer(2048);
        int i;
        byte[] buffer = new byte[2048];
        try{
            i = input.read(buffer);
        }catch(IOException e){
            i = -1;
        }
        for(int j = 0; j < i; j++){
            request.append((char)buffer[j]);
        }
        System.out.print(request.toString());
        uri = parseUri(request.toString());
    }
    
    private String parseUri(String requestString){
        int index1,index2;
        index1 = requestString.indexOf(' ');
        if(index1 != -1){
            index2 = requestString.indexOf(' ', index1 + 1);
            if(index2 > index1){
                return requestString.substring(index1 + 1, index2);
            }
        }
        return null;
    }
    
    public String getUri(){
        Config config = new Config();
//        String url = config.getIP() + ":" + config.getPort();
//        if(uri.lastIndexOf(url)==0)
        System.out.println("有人访问:"+ uri);
        if(uri == null){
            uri = "/";
        }
        
        if(uri.endsWith("/")){//以'/'结束,在后面添加默认文件
            uri += config.getDefaultHtmlFile();
        }
        if("/".equals(uri)){//只有'/',则为/index.html
            uri = "/"+config.getDefaultHtmlFile();
        }
        
        return uri;
    }
}


com.zxy97.server.Response.java

package com.zxy97.server;

import com.zxy97.server.file.Config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @作者 zhaoxuyang1997
 * @时间 2018-07-20 04:04
 * @版本 V1.0
 */
public class Response {
    private static final int BUFFER_SIZE = 1024;
    Request request;
    OutputStream output;
    public Response(OutputStream output){
        this.output = output;
    }
    public void setRequest(Request request){
        this.request = request;
    }
    public void sendStaticResource() throws IOException{
        byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        File file = new File(Config.WEB_ROOT, request.getUri());
        if(file.exists()){
            fis = new FileInputStream(file);
            int ch = fis.read(bytes, 0 , BUFFER_SIZE);
            while(ch != -1){
                output.write(bytes, 0, ch);
                ch = fis.read(bytes, 0, BUFFER_SIZE);
            }
        }else{
            String errorMessage = new Config().getMessageFileNotFound();
            output.write(errorMessage.getBytes());
        }
        if(fis != null){
           fis.close();         
        }
    }
    
}



com.zxy97.server.file.Config.java

package com.zxy97.server.file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Config {
    
    public static final String WEB_ROOT = System.getProperty("user.dir")+File.separator+"webroot";
    public static final String CONFIG_FOLDER = WEB_ROOT + File.separator + "config";
    public static final String CONFIG_FILE = CONFIG_FOLDER + File.separator + "config.properties";
    public static final String CSS_FILE = CONFIG_FOLDER + File.separator + "style.css";
    
    public String getIP(){
        return getValueByKey("ip");
    }
    public String getPort(){
        return getValueByKey("port");
    }
    public String getMessageFileNotFound(){
        return getValueByKey("message_file_not_found");
    }
    public String getHtmlTitle(){
        return getValueByKey("html_title");
    }
    public String getDefaultHtmlFile(){
        return getValueByKey("default_html_file");
    }
    private String getValueByKey(String key){
        return getValueByKey(CONFIG_FILE,key);
    }
    private String getValueByKey(String configFilePath, String key){
        String value;
        Properties prop = new Properties();
        try (InputStream in = new BufferedInputStream (new FileInputStream(configFilePath))) {
            prop.load(in);
            value = prop.getProperty(key);
            return value;
        }catch(IOException e){  
            System.out.println("未找到配置文件,正在尝试创建配置文件:");
            Create.createConfig();
            return getValueByKey(configFilePath,key);
        }
    }
}

com.zxy97.server.file.Create.java


package com.zxy97.server.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Create {
    static final String WEB_ROOT = Config.WEB_ROOT;
    static final String HTML_NAME = "index.html";
    
    public static void createConfig(){
        File configFolder = new File(Config.CONFIG_FOLDER);
        if(!configFolder.exists()){
            configFolder.mkdirs();
            System.out.printf("创建配置文件夹[%s]成功\n",configFolder.getAbsolutePath());
        }
        
        File configFile = new File(Config.CONFIG_FILE);
        if(!configFile.exists()){
            StringBuilder sb = new StringBuilder();
            sb.append("ip=127.0.0.1\r\n")
                    .append("port=80\r\n")
                    .append("message_file_not_found=File Not Found !\r\n")
                    .append("html_title=Java File Down - zxy97.com\r\n")
                    .append("default_html_file=index.html");
            try {
                writeToFile(sb,configFile.getAbsolutePath());
                System.out.printf("创建配置文件[%s]成功\n", configFile.getAbsolutePath());
            } catch (FileNotFoundException ex) {
                System.out.printf("创建配置文件[%s]失败\n", configFile.getAbsolutePath());
                Logger.getLogger(Create.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        File cssFile = new File(Config.CSS_FILE);
        if(!cssFile.exists()){
            StringBuilder css = new StringBuilder();
            css.append("body{width:960px;margin:20px auto;}a{outline-style: none;color: #68b12f;text-decoration: none}")
                    .append("a:hover{color: #9fd574;text-decoration: none}")
                    .append("table.style {margin-top:15px;border-collapse:collapse;border:1px solid #aaa;width:100%;font-size: 12px;}")
                    .append("table.style th {vertical-align:baseline;padding:5px 15px 5px 6px;background-color:#3F3F3F;border:1px solid #3F3F3F;text-align:left;color:#fff;font-size: 12px;}")
                    .append("table.style td {vertical-align:middle;padding:6px 15px 6px 6px;border:1px solid #aaa;font-size: 12px;}")
                    .append("table.style tr:nth-child(odd){background-color:#F5F5F5;}")
                    .append("table.style tr:nth-child(even){background-color:#fff;}"); 
            try {
                writeToFile(css,cssFile.getAbsolutePath());
                System.out.printf("创建配置文件[%s]成功\n", cssFile.getAbsolutePath());
            } catch (FileNotFoundException ex) {
                System.out.printf("创建配置文件[%s]失败\n", cssFile.getAbsolutePath());
                Logger.getLogger(Create.class.getName()).log(Level.SEVERE, null, ex);
            }
        }  
        
    }
    public static void createHtml(){
        String htmlPath = WEB_ROOT + File.separator + HTML_NAME;
        try {
            writeToFile(writeHtml(),htmlPath);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Create.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private static void writeToFile(StringBuilder content, String filePath) throws FileNotFoundException{
        PrintWriter pt = new PrintWriter(filePath);
        pt.append(content.toString());
        pt.flush();
    }
    private static StringBuilder writeHtml(){
        File folder = new File(WEB_ROOT);
        if(!folder.exists()){
            folder.mkdirs();
        }
        File[] files = folder.listFiles();
        StringBuilder sb = new StringBuilder();
        sb.append("<html>")
                .append("<head>")
//                .append("<meta charset=\"utf-8\">")
                .append("<title>").append(new Config().getHtmlTitle()).append("</title>")
                .append("<link href=\"config/style.css\" type=\"text/css\" rel=\"stylesheet\">")
                .append("</head>")
                .append("<body>")
                .append("<h3><a href=\"http://zxy97.com/\">zxy97</a>Java File Download Page</h3>")
                .append("<hr>")
                .append("<table class=\"style\">")
                .append("<tr><th>File-Name</th><th>File-Length</th><th>File-Last-Modified</th></tr>");
                
        //不要空文件,不要目录,不要index.html
        //要文件名称,大小,修改时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(File f:files){
            if(f.isDirectory()){
                continue;
            }
            String fileName = f.getName();
            if("index.html".equals(fileName)){
                continue;
            }
            
            long length = f.length();
            if(length==0){
                continue;
            }
            sb.append("<tr>")
                    .append("<td>").append("<a href=\"").append(fileName).append("\">").append(fileName).append("</a></td>")
                    .append("<td>").append(length/1024.0).append("KB").append("</td>")
                    .append("<td>").append(sdf.format(new Date(f.lastModified()))).append("</td>")
                    .append("</tr>");
        }
        
        sb.append("</table>")
                .append("</body>")
                .append("</html>");
        return sb;
    }
    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值