JavaでWeb HTTPサーバを実装してみる
2010/02/16 00:27Update
Java Socketで簡単なWeb HTTPサーバを実装したサンプルです。
簡単なWebサーバの実装手順
1)ServerSocket インスタンス生成
2)Webブラウザーなどのクライアントからの接続を待つ
3)接続されたら、スレッドを生成し、処理する
あ)リクエスト情報を取得する
い)リクエスト情報によってリソースをクライアントに返す
簡単なWebサーバの実装例
サンプルコード:
WebServer.javaimport java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author syboos.jp
* Webサーバー・エミュレーション
*
*/
public class WebServer {
private static final String PUBLIC_WEB_ROOT = "c:/website/";
public static void main(String args[]) {
int i = 1, PORT = 8080;
ServerSocket server = null;
try {
//サーバサイドのSocketインスタンスを生成
server = new ServerSocket(PORT);
System.out.println("Web Server is listening on port "
+ server.getLocalPort());
while (true) {
//接続待ち
Socket client = server.accept();
//接続処理スレッド
ConnectionThread ct = new ConnectionThread(client, i);
ct.start();
i++;
}
} catch (Exception e) {
System.out.println(e);
}
}
static class ConnectionThread extends Thread {
Socket client;
int counter;
public ConnectionThread(Socket cl, int c) {
client = cl;
counter = c;
}
//接続処理スレッド
public void run() {
try {
// クライアント IP
String destIP = client.getInetAddress().toString();
// クライアント ポート
int destport = client.getPort();
System.out.println("Connection " + counter + " :connected from "
+ destIP + " with port " + destport + ".");
PrintStream outstream = new PrintStream(client.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inline = reader.readLine();
while (reader.ready() && inline != null) {
System.out.println(inline);
inline = reader.readLine();
}
//レスポンス
//ここでは、単なるindex.htmlを返すだけ。実際のWebサーバは、リクエストとなるリソースを解析するし、それに相応しいコンテンツを返す必要があります
String responseFile = PUBLIC_WEB_ROOT + "index.html";
File file = new File(responseFile);
System.out.println(file.getName() + " requested.");
outstream.println("HTTP/1.0 200 OK");
outstream.println("MIME_version:1.0");
outstream.println("Content_Type:text/htm1");
int len = (int) file.length();
outstream.println("Content_Length:" + len);
outstream.println("");
sendfile(outstream, file);// ファイル転送
outstream.flush();
outstream.close();
} catch (Exception e) {
// TODO: handle exception
}
return;
}
/* ファイルを読み込み、ブラウザーへ書き込み(応答) */
void sendfile(PrintStream outs, File file) {
try {
DataInputStream in = new DataInputStream(
new FileInputStream(file));
int len = (int) file.length();
byte buf[] = new byte[len];
in.readFully(buf);
outs.write(buf, 0, len);
outs.flush();
in.close();
} catch (Exception e) {
System.out.println("Error sending file.");
System.exit(1);
}
}
}
}
上のWebサーバは、8080というポートで待ち受けていて、クライアントからの接続要求があった場合、c:/website/にある index.html ファイルを読み込み、クライアントに送信します。
では、実行してみます。
1)C:\websiteフォルダに適当な内容のindex.htmlファイルを作成します。
index.html
<html> <head> <title>From My Web Server</title> </head> <body> こんにちは、TEST My Web Server. </body> </html>
2)コマンドウィンドウからWebサーバを起動する
java WebServer
3)ブラウザーのアドレスにhttp://localhost:8080/
や
http://localhost:8080/hello.htm
などを入力します
4)すると、ウィンドウに次のような情報が表示されます。
Connecction2:connected to /127.0.0.1 on port1443.
GET /hello HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; ja; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: ja,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: Shift_JIS,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie:
index.html requested.
GET /hello HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; ja; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: ja,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: Shift_JIS,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie:
index.html requested.
Webブラウザーの画面にてindex.htmlが表示されます。
こんにちは、TEST My Web Server.
Webサーバ - Wikipedia
Sponsored Link
- Relative Articles
- Oracle JRockit JVM - 高性能Java VM - (2010/12/21 12:03)
- DTDファイル処理 - DTDParser - Java DTD パーサー - (2009/01/30 17:48)
- Apache Commons EmailによるEメール送信 - (2009/02/06 17:51)
- Jakarta Commons によるHTTP処理(HttpClient) - (2009/02/17 15:14)
- PSD-parser - JavaでPSDファイルを抽出するためのライブラリ - (2009/04/21 00:09)
- HttpClient のuser-agent 設置 - (2009/06/10 17:42)
- Lobo Java Web Browser - オープンソースJava Webブラウザー - (2009/06/10 18:30)
- MockFtpServer - Ftpサーバのモック実装 - (2009/06/25 14:50)
- Commons HttpClient PostMethodで日本語パラメータ例 - (2011/05/31 00:34)
- Tomcat5 サーブレット/JSP コンテナ SSL設定の手引き - (2009/03/13 16:29)