LoginSignup
0
1

More than 5 years have passed since last update.

Kotlin Script でシンプルなサーバを作る

Last updated at Posted at 2018-10-23

Kotlin は Script としても使えるという利点があります。 つまり、 いちいち(明示的に)コンパイルしなくても利用可能ということです。

スクリプトとして使えるなら、 Python の CGIHTTPServer みたいに簡単にサーバを立ち上げられてもいいんじゃないかと思い、 コードを書いてみました。
(GitHub: Kotlin-Simple-HTTP-Server にあります。)
ちょっとした HTMLファイルの見栄えをブラウザでチェックしたいというようなニーズには応えることができます。

準備

Kotlin のコンパイラをインストールします。

macOS の場合

brew install kotlin で Kotlin (kotlinc) をインストールします。
私の環境では、 /usr/local/Cellar/kotlin/1.2.71/bin/kotlinc でした。

コード

ソケット通信を行うコードを書きます。
JVM で動かす前提です。 Java のコードを書き換えたような状態です。

server.kts
import java.io.*
import java.net.ServerSocket

val port = 8081;
val serverSocket = ServerSocket(port);
println("listening port: " + port.toString());

lateinit var requestLine: String
while (true) {
    val clientSocket = serverSocket.accept();

    val `in` = BufferedReader(InputStreamReader(clientSocket.getInputStream()));
    val out = BufferedWriter(OutputStreamWriter(clientSocket.getOutputStream()));

    do {
        requestLine = `in`.readLine()
        println(requestLine);
    } while (!requestLine.isNullOrEmpty())

    val body = """
        <!DOCTYPE html><html><head><title>Exemple</title></head><body><p>Server exemple.</p></body></html>
    """.trimIndent()

    out.write("HTTP/1.0 200 OK\r\n");
    out.write("Date: Fri, 31 Dec 2017 23:59:59 GMT\r\n");
    out.write("Server: Apache/0.8.4\r\n");
    out.write("Content-Type: text/html\r\n");
    out.write("Content-Length: ${body.toByteArray().size}\r\n");
    out.write("Expires: Sat, 01 Jan 2020 00:59:59 GMT\r\n");
    out.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMT\r\n");
    out.write("\r\n");
    out.write(body)

    out.close();
    `in`.close();
    clientSocket.close();
}

(CGIHTTPServer のようなフォームの値の簡単に取得する方法は見つかっていないのですが。)

実行する

kotlinc -script server.kts

localhost:8081 にブラウザからアクセスするとページが表示されます。

関連

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1