Skip to content

Instantly share code, notes, and snippets.

@sinmetal
Forked from u1aryz/gist:2644671
Last active August 29, 2015 14:06
Show Gist options
  • Save sinmetal/aa3e9b07c77b273fba64 to your computer and use it in GitHub Desktop.
Save sinmetal/aa3e9b07c77b273fba64 to your computer and use it in GitHub Desktop.
package org.sinmetal.http;
import java.io.*;
import java.net.*;
/**
* 簡易HTTPサーバ
*
*/
public class Server {
private static final int PORT = 8080;
public static void main(String[] args) throws IOException {
System.out.println("start up http server...");
ServerSocket serverSocket = null;
Socket socket = null;
PrintWriter writer = null;
BufferedReader br = null;
try {
serverSocket = new ServerSocket(PORT);
while (true) {
socket = serverSocket.accept();
System.out.println("request incoming...");
// リクエスト
// header
br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
final String CONTENT_LENGTH = "Content-Length:";
int contentLength = -1;
String str;
while (!(str = br.readLine()).equals("")) {
System.out.println(str);
if (str.indexOf(CONTENT_LENGTH) > -1) {
contentLength = new Integer(str.substring(
str.indexOf(CONTENT_LENGTH)
+ CONTENT_LENGTH.length() + 1,
str.length())).intValue();
}
}
// body
if (contentLength > -1) {
char[] charArray = new char[contentLength];
br.read(charArray, 0, contentLength);
String body = new String(charArray);
System.out.println(body);
}
// レスポンス
writer = new PrintWriter(socket.getOutputStream(), true);
StringBuilder builder = new StringBuilder();
builder.append("HTTP/1.1 200 OK").append("\n");
builder.append("Content-Type: text/html").append("\n");
builder.append("\n");
builder.append("<html><head><title>Hello world!</title></head><body><h1>Hello world!</h1>Hi!</body></html>");
System.out.println("responce...");
System.out.println(builder.toString() + "\n");
writer.println(builder.toString());
socket.close();
}
} finally {
if (serverSocket != null) {
serverSocket.close();
}
if (socket != null) {
socket.close();
}
if (writer != null) {
writer.close();
}
if (br != null) {
br.close();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment