JavaでWeb HTTPサーバを実装してみる

2010/02/16 00:27Update
TAGS: Webサーバー | エミュレーション | HTTP | サンプル | ServerSocket | Socket

Java Socketで簡単なWeb HTTPサーバを実装したサンプルです。

簡単なWebサーバの実装手順


1)ServerSocket インスタンス生成
2)Webブラウザーなどのクライアントからの接続を待つ
3)接続されたら、スレッドを生成し、処理する
  あ)リクエスト情報を取得する
  い)リクエスト情報によってリソースをクライアントに返す

簡単なWebサーバの実装例


サンプルコード:
WebServer.java
import 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.

Webブラウザーの画面にてindex.htmlが表示されます。
こんにちは、TEST My Web Server. 


Webサーバ - Wikipedia

有关作者
Syboos.jp編集長AJavaやオープンソース情報の執筆、Webサイトの開発や運営全般の業務に携わる。

Sponsored Link


Comments