-
-
Save sinmetal/aa3e9b07c77b273fba64 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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