Main : Implement basic http server.
This commit is contained in:
parent
4c6228e2f1
commit
fd8116cfc8
|
@ -1,6 +1,52 @@
|
||||||
package com.voronind.doublegis.test
|
package com.voronind.doublegis.test
|
||||||
|
|
||||||
@main
|
import com.sun.net.httpserver.{HttpExchange, HttpHandler, HttpServer}
|
||||||
def main(): Unit = {
|
|
||||||
println("Hello world!")
|
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()
|
||||||
|
}
|
||||||
}
|
}
|
Reference in a new issue