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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
| import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.activation.MimetypesFileTypeMap;
public class HttpServer {
public static void main(String[] args) {
if ( args.length==0 ) {
int port = 8088;
Path path = Paths.get(System.getProperty("user.dir"));
launch(port, path);
}
else if ( args.length==1 ) {
int port = Integer.parseInt(args[0]);
Path path = Paths.get("");
launch(port, path);
}
else {
int port = Integer.parseInt(args[0]);
Path path = Paths.get(args[1]);
if ( Files.isDirectory(path)) {
launch(port, path);
}
else {
System.err.println("Directory not found: " + path);
}
}
}
private static void launch(int port, Path path) {
HttpServer server = new HttpServer(port, path);
Runtime.getRuntime().addShutdownHook(new Thread(()->server.stop()));
try {
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private final int httpPort;
private final Path path;
private boolean started;
private ServerThread serverThread;
public HttpServer(int httpPort, Path path) {
this.httpPort=httpPort;
this.path=path;
}
public synchronized void start() throws IOException {
if ( !started ) {
started = true;
serverThread = new ServerThread(httpPort);
serverThread.start();
}
}
public synchronized void stop() {
if ( started ) {
serverThread.stopThread();
started=false;
}
}
private class ServerThread extends Thread {
private final ServerSocket server;
private volatile boolean running;
private ExecutorService executor;
public ServerThread(int port) throws IOException {
super("Http server thread ("+port+")");
this.server = new ServerSocket(port);
}
@Override
public synchronized void start() {
running=true;
try {
super.start();
}
catch(IllegalStateException e) {
running=false;
}
}
@Override
public void run() {
executor = Executors.newSingleThreadExecutor();
while(running) {
try {
Socket accepted = server.accept();
executor.execute(()-> processAccepted(accepted));
} catch (IOException e) {
if ( running ) {
e.printStackTrace();
running=false;
}
}
}
executor.shutdown();
}
private void processAccepted(Socket accepted) {
try(BufferedReader reader = new BufferedReader(new InputStreamReader(accepted.getInputStream()))) {
// simplifié à l'extrême
String line = reader.readLine();
String filename = line.split(" ")[1];
if ( "/".equals(filename) ) {
filename = "/index.html";
}
Path fullpath = path.resolve(filename.substring(1));
if ( Files.exists(fullpath) ) {
String mimetype = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(filename);
respond(accepted, mimetype, fullpath, filename);
}
else {
respondError(accepted, "Not found: " + filename);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopThread() {
running=false;
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
interrupt();
}
}
private void respond(Socket accepted, String mimetype, Path fullpath, String reason) throws IOException {
try(OutputStream outputStream = accepted.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);) {
printStream.print("HTTP-Version 1.0 Status-Code "+200+" \r\n");
printHeader(printStream,"Content-type", mimeType);
printHeader(printStream,"Content-length", Files.size(fullpath));
printStream.print("\r\n");
try(InputStream inputStream = new BufferedInputStream(Files.newInputStream(fullpath))) {
byte[] buffer = new byte[2048];
for(int read = inputStream.read(buffer); read!=-1; read = inputStream.read(buffer)) {
outputStream.write(buffer, 0, read);
}
}
}
}
private void respondError(Socket accepted, String string) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("<html><body>");
sb.append(string);
sb.append("</body></html>");
respond(accepted, 500, sb, string);
}
private void respond(Socket accepted, int code, StringBuilder sb, String reason) throws IOException {
try(PrintStream printStream = new PrintStream(accepted.getOutputStream())) {
printStream.print("HTTP-Version 1.0 Status-Code "+code+" "+reason+"\r\n");
printHeader(printStream,"Content-type", "text/html");
printHeader(printStream,"Content-length", sb.length());
printStream.print("\r\n");
printStream.print(sb);
}
}
private void printHeader(PrintStream printStream, String name, Object value) {
printStream.print(name);
printStream.print(": " );
printStream.print(value);
printStream.print("\r\n");
}
} |
Partager