2018년 11월 1일 목요일

[Java] WebServer Example (NanoHttpd)


NanoHttpd Home: https://github.com/NanoHttpd/nanohttpd

Tiny, easily embeddable HTTP server in Java. (single source file)



1. WebServer Example

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
96
97
98
99
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;

import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.Response.Status;

public class WebServer extends NanoHTTPD {
    
    NanoHTTPD nano;
    String baseFolder;

    public static void main(String[] args) {
        try {
            WebServer nano = new WebServer(8880);
            nano.setBaseFolder("D:\\Temp");
            nano.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
        } catch (IOException ioe) {
            System.err.println("Couldn't start server:\n" + ioe);
        }
    }

    public WebServer(int port) throws IOException {
        super(port);
        System.out.println("\nRunning! Point your browsers to http://localhost:8080/ \n");
    }

    public void setBaseFolder(String folder) {
        baseFolder = folder;
    }

    private String trimPrefix(String text, String prefix) {
        if( text.startsWith(prefix) ) {
            text = text.substring(prefix.length());
        }
        return text;
    }
    
    private String getDirectoryList(File folder, String uri) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        File[] files = folder.listFiles();
        StringBuilder sb = new StringBuilder();
        sb.append("<html><head><style type=\"text/css\" scoped>\r\n" + 
                " table, th, td { border: 1px solid gray; border-collapse: collapse; } \r\n" + 
                " a { text-decoration: none;\r\n" + 
                " } \r\n" + 
                "</style></head><body>\r\n"+
                "<h5> Folder: "+uri+"</h5>\r\n" +
                "<table><thead>\r\n" + 
                "<tr>\r\n" + 
                "  <th>Filename</th>\r\n" + 
                "  <th>Size <small>(bytes)</small></th>\r\n" + 
                "  <th>Date Modified</th>\r\n" + 
                "</tr>\r\n" + 
                "</thead><tbody>");
        
        if( ! folder.equals(new File(baseFolder)) ) {
            sb.append("<tr>\r\n");
            sb.append("<td><a href=\"" + trimPrefix(folder.getParent(), baseFolder) + "\">..</a></td>");
            sb.append("<td align=\"right\">&lt;DIR&gt;</td>");
            sb.append("<td>&nbsp;</td>");
            sb.append("</tr>\r\n");
        }
        
        for( File file : files ) {
            sb.append("<tr>\r\n");
            sb.append("<td><a href=\"" + trimPrefix(file.getPath(), baseFolder) + "\">"); sb.append(file.getName()); sb.append("</a></td>");
            if( file.isDirectory() ) {
                sb.append("<td align=\"right\">&lt;DIR&gt;</td>");
            } else {
                sb.append("<td align=\"right\">"); sb.append(""+file.length()); sb.append("</td>");
            }
            sb.append("<td>"); sb.append(""+sdf.format(file.lastModified())); sb.append("</td>");
            sb.append("</tr>\r\n");
        }
        sb.append("</tbody></table></body></html>");
        System.out.println("RESPONSE: " + sb.toString());
        return sb.toString();
    }
    
    @Override
    public Response serve(IHTTPSession session) {
        System.out.println("URI: " + session.getUri());
        String uri = session.getUri();
        File file = new File(baseFolder, uri);
        if( file.isDirectory() ) {
            return newFixedLengthResponse(getDirectoryList(file,uri));
        } else {
            try {
                return newFixedLengthResponse(Status.OK, NanoHTTPD.MIME_PLAINTEXT, new FileInputStream(file), file.length());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return newFixedLengthResponse("");
            }
        }
    }
}


Output:



댓글 없음:

댓글 쓰기