Ktor Hello World程序路由无响应问题求助
问题:Ktor Hello World程序返回"Empty reply from server"且无日志输出
我用Kotlin和Ktor编写了如下Hello World程序:
suspend fun main() { val server = embeddedServer(Netty, port = 8080, host = "localhost") { println("1") install(CallLogging) { level = Level.ERROR } println("2") routing { println("2.1") get { println("2.1.1") call.respondText("Hello, World!") } } println("3") } println("done") server.start(wait = true) println("end") }
当访问http://localhost:8080/时,服务器返回"Empty reply from server",且无对应日志输出。多次尝试后的程序输出日志如下:
done [main] INFO ktor.application - Autoreload is disabled because the development mode is off. 1 2 2.1 3 [main] INFO ktor.application - Application started in 0.043 seconds. [main] ERROR ktor.application - Application started: io.ktor.server.application.Application@516be40f [DefaultDispatcher-worker-1] INFO ktor.application - Responding at http://localhost:8080
我尝试移除host参数改用0.0.0.0,问题仍未解决,请问该问题的原因可能是什么?
可能的原因及解决办法
路由未显式指定根路径
较新版本的Ktor中,无参数的get { ... }不再默认匹配根路径/,必须显式声明路径才能正确匹配请求。修改路由代码为:routing { println("2.1") get("/") { // 显式指定根路径 println("2.1.1") call.respondText("Hello, World!") } }main函数不必要的suspend修饰
server.start(wait = true)是阻塞式调用,无需将main声明为suspend函数。移除suspend修饰符,避免协程上下文可能引发的初始化异常:fun main() { // 去掉suspend修饰符 val server = embeddedServer(Netty, port = 8080, host = "localhost") { // 原有初始化代码 } println("done") server.start(wait = true) println("end") }验证路由匹配逻辑
可以添加一个匹配所有路径的路由测试是否能命中请求,确认路由系统是否正常工作:routing { get("/*") { println("路由已命中") call.respondText("Path Matched") } }如果这个路由能触发输出,说明之前的根路径匹配写法不符合当前Ktor版本的规则。
内容的提问来源于stack exchange,提问作者rascio
相关产品推荐
相关产品推荐

