Main : Implement basic http server.

This commit is contained in:
Dmitry Voronin 2024-09-23 15:16:58 +03:00
parent 4c6228e2f1
commit fd8116cfc8
Signed by: voronind
SSH key fingerprint: SHA256:3kBb4iV2ahufEBNq+vFbUe4QYfHt98DHQjN7QaptY9k

View file

@ -1,6 +1,52 @@
package com.voronind.doublegis.test
@main
def main(): Unit = {
import com.sun.net.httpserver.{HttpExchange, HttpHandler, HttpServer}
import java.io.{InputStream, OutputStream}
import java.net.InetSocketAddress
import scala.language.postfixOps
@main def main(): Unit = {
println("Hello world!")
val server = HttpServer.create(new InetSocketAddress(8000), 0)
server.createContext("/", new RootHandler())
server.setExecutor(null)
server.start()
println("Hit any key to exit...")
System.in.read()
server.stop(0)
}
class RootHandler extends HttpHandler {
def handle(t: HttpExchange): Unit = {
displayPayload(t.getRequestBody)
sendResponse(t)
}
private def displayPayload(body: InputStream): Unit = {
println()
println("**** Start ****")
println()
copyStream(body, System.out)
println()
println("**** End ****")
println()
}
private def copyStream(in: InputStream, out: OutputStream): Unit = {
Iterator
.continually(in.read)
.takeWhile(-1 !=)
.foreach(out.write)
}
private def sendResponse(t: HttpExchange): Unit = {
val response = "Ack!"
t.sendResponseHeaders(200, response.length())
val os = t.getResponseBody
os.write(response.getBytes)
os.close()
}
}