KTor 站点无法访问

2024-03-22

我想使用 ktor 制作一个简单的 http 服务器。但是,当我输入该站点(127.0.0.1:8080 或 0.0.0.0:8080)时,它就不存在。它不打印也不响应。
但是,如果我使用 NanoHttpd 而不是 ktor,则一切正常。我的问题是什么?

import io.ktor.application.call
import io.ktor.http.ContentType
import io.ktor.response.respondText
import io.ktor.routing.get
import io.ktor.routing.routing
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty


fun main() {
    val server = embeddedServer(Netty, port = 8080) {
        routing {
            get("/") {
                println("TEST")
                call.respondText("Hello World!", ContentType.Text.Plain)
            }
        }
    }
    server.start(wait = true)
}

输出只是:

[main] INFO ktor.application - No ktor.deployment.watch patterns specified, automatic reload is not active
[main] INFO ktor.application - Responding at http://0.0.0.0:8080

它可能是以下情况之一:

  1. 申请代码
  2. 运行配置

我倾向于运行配置而不是应用程序代码存在问题。

应用代码

尽管我认为您的问题与运行配置有关,但如果不是,我将在此处提供示例代码。

当我使用IntelliJ Ktor 插件 https://plugins.jetbrains.com/plugin/10823-ktor,Ktor 应用程序的引导如下:

应用程序.kt

package com.example

import io.ktor.application.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

@kotlin.jvm.JvmOverloads
@Suppress("unused") // Referenced in application.conf
fun Application.module(testing: Boolean = false) {
    routing {
        get("/") {
            call.respondText("Hello, world!", ContentType.Text.Plain)
        }
    }
}

应用程序配置文件

ktor {
    deployment {
        port = 8080
        port = ${?PORT}
    }
    application {
        modules = [ com.example.ApplicationKt.module ]
    }
}

我在这里提供了一个示例 Ktor 代码库:https://gitlab.com/tinacious/ktor-example https://gitlab.com/tinacious/ktor-example

运行配置

它可能是您在 IntelliJ 中的运行配置。它需要设置为 Kotlin 脚本(而不是应用程序)。当它设置为应用程序时,我收到与您相同的错误。以下是如何设置我的运行配置,使我能够在 IntelliJ 中运行服务器:

  1. 添加配置
  2. Choose Kotlin 脚本从模板部分。不要选择应用程序。
  3. 在底部附近显示“使用模块的类路径”的地方,选择您的application.main.
  4. 在顶部附近写着“主类”的地方,您应该能够选择您的主要应用程序。我发现这只在我选择模块的类路径后才出现。

以下是配置中的相关部分:

这是我在步骤 4 中描述的内容,即添加类路径后我可以选择我的主类:

运行符号应该是 Kotlin 徽标:

我建议安装IntelliJ Ktor 插件 https://plugins.jetbrains.com/plugin/10823-ktor用于引导您的项目。它使用 Gradle 并引导一切,所以当你运行时./gradlew run,您正在正确运行它,并且无需手动构建配置步骤即可访问它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

KTor 站点无法访问 的相关文章

随机推荐