首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >KTor站点不可达

KTor站点不可达
EN

Stack Overflow用户
提问于 2020-07-03 09:29:18
回答 1查看 1.6K关注 0票数 2

我想使用ktor制作一个简单的http服务器。但是,当我输入站点(127.0.0.1:8080或0.0.0:8080)时,它只是不存在。它不打印也不回应。

但是,如果我使用NanoHttpd而不是ktor,那么一切都很好。我的问题是什么?

代码语言:javascript
复制
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)
}

产出只是:

代码语言:javascript
复制
[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
EN

回答 1

Stack Overflow用户

发布于 2020-12-18 01:42:09

这可能是以下几点之一:

  1. 应用程序代码
  2. 运行配置

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

应用程序代码

尽管我认为您的问题在于运行配置,但如果不是,我在这里提供示例代码。

当我使用IntelliJ Ktor插件时,Ktor应用程序被引导如下:

Application.kt

代码语言:javascript
复制
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

代码语言:javascript
复制
ktor {
    deployment {
        port = 8080
        port = ${?PORT}
    }
    application {
        modules = [ com.example.ApplicationKt.module ]
    }
}

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

运行配置

这可能是您在IntelliJ中的运行配置。它需要设置为Kotlin脚本(而不是应用程序)。当它被设置为一个应用程序时,我会得到与您相同的错误。下面是如何设置我的运行配置,允许我在IntelliJ中运行服务器:

  1. 添加配置
  2. 从模板部分选择Kotlin脚本。不要选择“应用程序”。
  3. 在底部附近,上面写着“使用模块类路径”,选择您的application.main
  4. 在上面写着“主类”的地方,你应该可以选择你的主应用程序。我只在选择模块的类路径之后才发现这一点。

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

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

run符号应该是Kotlin徽标:

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62712508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档