CodeBlanks Logo Icon CodeBlanks

Ktor server

Learn HTTP servers with Ktor server.

What is Ktor server?

Ktor server is a coroutine based framework for writing HTTP servers in Kotlin. It works with engines like Netty, Jetty or CIO.

A server is started with the embeddedServer function. Example: embeddedServer(Netty, port = 8080) { ... }.start(wait = true). Routing and plugins are declared inside this block. Because it is coroutine based, each request is handled as a coroutine; this differs from a thread per request model. In this lesson you will set up the basic server skeleton.

Engine choice

A Ktor server runs on an engine. On JVM the common choices are Netty, Jetty and CIO.

The engine handles sockets and request dispatch. In embeddedServer(Netty, port = 8080) { ... } the engine is the first parameter. Netty is a common, mature choice for production. CIO is written in Kotlin and needs no extra dependency. The choice depends on performance and dependency needs.

Practice Set up the server skeleton

Define a server with val server = embeddedServer(Netty, port = 8080) { }. Print println("Server ready").

Starter code

Main.kt
// Ktor server
// write here
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*

fun main() {
    
}

Sample solution

Main.kt
fun main() {
    val server = embeddedServer(Netty, port = 8080) {
    }
    println("Server ready")
}

Expected output

Server ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is a Ktor server started?

  • main()
  • HttpClient()
  • embeddedServer() Correct answer
  • runBlocking()

Explanation: The embeddedServer function starts the server.

2 Complete the embeddedServer call

Question
val server = ____(Netty, port = 8080) {
    
}
Answer
val server = embeddedServer(Netty, port = 8080) {
    
}

Explanation: embeddedServer starts the server.

3 Match Ktor server parts

Term Meaning
embeddedServer Starts server
Netty Engine
port Port number
routing Route definition

All lessons in Advanced