Table of Contents
Kotlin can be used as script. I tried to create simple server with Kotlin script, like the server introduced in Python Light Server.
Preparation
Install Kotlin compiler.
macOS case
If you use homebrew, you can install Kotlin (kotlinc) with brew install kotlin
. In my case, it was installed as /usr/local/Cellar/kotlin/1.2.71/bin/kotlinc
.
Code
It is a socket connection code with java.net.ServerSocket
. The code is in GitHub: Kotlin-Simple-HTTP-Server, too.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
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 OKrn"); out.write("Date: Fri, 31 Dec 2017 23:59:59 GMTrn"); out.write("Server: Apache/0.8.4rn"); out.write("Content-Type: text/htmlrn"); out.write("Content-Length: ${body.toByteArray().size}rn"); out.write("Expires: Sat, 01 Jan 2020 00:59:59 GMTrn"); out.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMTrn"); out.write("rn"); out.write(body) out.close(); `in`.close(); clientSocket.close(); } |
Launch Server
Launch server with the following command.
1 |
kotlinc -script server.kts |
When you access to localhost:8081
, you can see the page.