Ktor 1.6.8 Help

Creating a server

To run a Ktor server application, you need to create a server first. Server configuration can include different settings: a server engine (such as Netty, Jetty, etc.), various engine-specific options, host and port values, and so on. There are two main approaches in Ktor for creating and running a server:

  • The embeddedServer function is a simple way to configure server parameters in code and quickly run an application.

  • EngineMain provides more flexibility to configure a server. You can specify server parameters in an application.conf file and change a configuration without recompiling your application. Moreover, you can run your application from a command line and override the required server parameters by passing corresponding command-line arguments.

embeddedServer

The embeddedServer function is a simple way to configure server parameters in code and quickly run an application. In the code snippet below, it accepts an engine and port as parameters to start a server. In the example below, we run a server with the Netty engine and listen on the 8080 port:

package com.example import io.ktor.application.* import io.ktor.response.* import io.ktor.routing.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main() { embeddedServer(Netty, port = 8080) { routing { get("/") { call.respondText("Hello, world!") } } }.start(wait = true) }

You can find the full example here: embedded-server.

EngineMain

EngineMain starts a server with the selected engine and loads the application module specified in the external application.conf file. Besides modules to load, this file can include various server parameters (the 8080 port in the example below).

package com.example import io.ktor.application.* import io.ktor.response.* import io.ktor.routing.* fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args) fun Application.module(testing: Boolean = false) { routing { get("/") { call.respondText("Hello, world!") } } }
ktor { deployment { port = 8080 } application { modules = [ com.example.ApplicationKt.module ] } }

You can find the full example here: engine-main.

Last modified: 11 May 2022