소켓 손 글씨 HTTP 서버
public class JHttp {
private static final Logger logger = Logger.getLogger(JHttp.class.getCanonicalName());
private static final int NUM_THREADS = 50;
private static final String INDEX_FILE = "index.html";
private final File rootDirectory;
private final int port;
public JHttp(File rootDirectory, int port) {
this.rootDirectory = rootDirectory;
this.port = port;
}
public void start() throws IOException {
ExecutorService pool = Executors.newFixedThreadPool(NUM_THREADS);
try (ServerSocket server = new ServerSocket(port)) {
logger.info("Accepting connections on port " + server.getLocalPort());
logger.info("Document Root: " + rootDirectory);
while (true) {
try {
Socket request = server.accept();
RequestProcessor r = new RequestProcessor(rootDirectory, INDEX_FILE, request);
pool.submit(r);
} catch (IOException e) {
logger.log(Level.WARNING, "Error accepting connection", e);
}
}
}
}
public static void main(String[] args) {
try {
URL url = JHttp.class.getClassLoader().getResource("static");
JHttp jHttp = new JHttp(new File(url.getPath()), 8888);
jHttp.start();
} catch (IOException e) {
logger.log(Level.SEVERE, "server could not start", e);
}
}
private class RequestProcessor implements Runnable {
private File rootDirectory;
private String indexFileName = "index.html";
private Socket connection;
public RequestProcessor(File rootDirectory, String indexFileName, Socket connection) {
this.rootDirectory = rootDirectory;
this.indexFileName = indexFileName;
this.connection = connection;
}
@Override
public void run() {
//
String root = rootDirectory.getPath();
try {
OutputStream raw = new BufferedOutputStream(connection.getOutputStream());
Writer out = new OutputStreamWriter(raw);
Reader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream()));
// GET /xxx HTTP/1.1
StringBuilder requestLine = new StringBuilder();
while (true) {
int c = in.read();
if (c == '\r' || c == '
') {
break;
}
requestLine.append((char) c);
}
String get = requestLine.toString();
logger.info(connection.getRemoteSocketAddress() + " " + get);
String[] tokens = get.split("\\s+");
String method = tokens[0];
String version = "";
if ("GET".equals(method)) {
String fileName = tokens[1];
if (fileName.endsWith("/")) {
fileName += indexFileName;//
}
// MIME
String contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName);
if (tokens.length > 2) {
version = tokens[2];
}
File theFile = new File(rootDirectory, fileName.substring(1, fileName.length()));
if (theFile.canRead() && theFile.getCanonicalPath().startsWith(root)) {
// ,
byte[] theData = Files.readAllBytes(theFile.toPath());
if (version.startsWith("HTTP/")) { // MIME
sendHeader(out, "HTTP/1.1 200 OK", contentType, theData.length);
}
// , , writer
raw.write(theData);
raw.flush();
} else {
//
String body = new StringBuilder("\r
")
.append("File not Find \r
")
.append("")
.append("HTTP Error 404 : File Not Found\r
")
.append("\r
")
.toString();
sendHeader(out, "HTTP/1.1 404 FileNotFound", "text/html; charset=utf-8", body.length());
out.write(body);
out.flush();
}
} else {
//
//
String body = new StringBuilder("\r
")
.append("File not Find \r
")
.append("")
.append("HTTP Error 501 : Not Support\r
")
.append("\r
")
.toString();
sendHeader(out, "HTTP/1.1 501 Not Support", "text/html; charset=utf-8", body.length());
out.write(body);
out.flush();
}
out.close();
in.close();
} catch (IOException e) {
logger.log(Level.WARNING, "Error talking to " + connection.getRemoteSocketAddress(), e);
} finally {
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void sendHeader(Writer out, String responseCode, String contentType, int length) throws IOException {
out.write(responseCode + System.lineSeparator());
out.write("Date: " + new Date() + System.lineSeparator());
out.write("Server: JHTTP 1.0" + System.lineSeparator());
out.write("Content-length: " + length + System.lineSeparator());
out.write("Content-type: " + contentType + System.lineSeparator() + System.lineSeparator()); //
out.flush();
}
}
}
추가 가능 한 추가 기능: 1. 서버 관리 페이지 2. Java Servlet API 지원 3. POST, PUT 4 와 같은 다른 요청 방법 을 지원 합 니 다. 다 중 문서 루트 디 렉 터 리 지원
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.