Skip to content

Native 伺服器 ​

程式碼範例: embedded-server-native

Ktor 支援 Kotlin/Native,可讓您在無需額外執行階段或虛擬機的情況下執行伺服器。目前在 Kotlin/Native 下執行 Ktor 伺服器具有以下限制:

在 Kotlin/Native 專案中使用 Ktor 需要新的記憶體管理器,自 Kotlin 1.7.20 起預設啟用。

新增相依性 ​

Kotlin/Native 專案中的 Ktor 伺服器至少需要兩個相依性:

  • ktor-server-core(核心相依性)
  • ktor-server-cio(CIO 引擎)

以下範例將相依性新增至 build.gradle.kts 檔案中的 nativeMain 原始碼集:

kotlin
kotlin {
    sourceSets {
        nativeMain.dependencies {
            implementation(ktorLibs.server.core)
            implementation(ktorLibs.server.cio)
        }
    }
}
上述程式碼片段使用 Ktor 版本目錄來指定 Ktor 相依性。

若要測試 Native 伺服器,請將 ktor-server-test-host 產物新增至 nativeTest 原始碼集:

kotlin
kotlin {
    sourceSets {
        nativeTest.dependencies {
            implementation(libs.kotlin.test)
            implementation(ktorLibs.server.testHost)
        }
    }
}

設定原生目標 ​

指定所需的原生目標,並使用 binaries 屬性宣告原生二進位檔:

kotlin
kotlin {
    val hostOs = System.getProperty("os.name")
    val arch = System.getProperty("os.arch")
    val nativeTarget = when {
        hostOs == "Mac OS X" && arch == "x86_64" -> macosX64("native")
        hostOs == "Mac OS X" && arch == "aarch64" -> macosArm64("native")
        hostOs == "Linux" && (arch == "x86_64" || arch == "amd64") -> linuxX64("native")
        hostOs == "Linux" && arch == "aarch64" -> linuxArm64("native")
        hostOs.startsWith("Windows") -> mingwX64("native")
        // 其他支援的目標列在此處:https://ktor.io/docs/server-native.html#targets
        else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
    }

    nativeTarget.apply {
        binaries {
            executable {
                entryPoint = "main"
            }
        }
    }
}

如需完整範例,請參閱 embedded-server-native。

後續步驟 ​

設定好 Gradle 建置指令碼後,即可繼續建立 Ktor 伺服器。