我想使用ktor制作一个简单的http服务器。但是,当我输入站点(127.0.0.1:8080或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发布于 2020-12-18 01:42:09
这可能是以下几点之一:
我倾向于认为运行配置存在问题,而不是应用程序代码。
应用程序代码
尽管我认为您的问题在于运行配置,但如果不是,我在这里提供示例代码。
当我使用IntelliJ Ktor插件时,Ktor应用程序被引导如下:
Application.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)
}
}
}application.conf
ktor {
deployment {
port = 8080
port = ${?PORT}
}
application {
modules = [ com.example.ApplicationKt.module ]
}
}我在这里提供了一个示例Ktor代码库:https://gitlab.com/tinacious/ktor-example
运行配置
这可能是您在IntelliJ中的运行配置。它需要设置为Kotlin脚本(而不是应用程序)。当它被设置为一个应用程序时,我会得到与您相同的错误。下面是如何设置我的运行配置,允许我在IntelliJ中运行服务器:
application.main。以下是配置中的相关部分:

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

run符号应该是Kotlin徽标:

我建议安装用于引导项目的IntelliJ Ktor插件。它使用Gradle和引导所有东西,因此当您运行./gradlew run时,您将正确地运行它,并且无需手动构建配置步骤就可以访问它。
https://stackoverflow.com/questions/62712508
复制相似问题