我找到了一个不安全的ktor websocket服务器(ws://...)的文档:https://ktor.io/docs/creating-web-socket-chat.html#creating-the-chat-client。
我找到了一个安全的ktor http服务器(https://...)的文档:https://github.com/ktorio/ktor-documentation/tree/main/codeSnippets/snippets/ssl-embedded-server。
但我似乎找不到或弄不清楚如何提供一个安全的ktor websocket服务器(wss://...)。
我不想使用像nginx这样的SSL反向代理。
编辑:以下是代码:
我找到了一个安全的ktor http服务器(https://...)的文档:https://github.com/ktorio/ktor-documentation/tree/main/codeSnippets/snippets/ssl-embedded-server。
但我似乎找不到或弄不清楚如何提供一个安全的ktor websocket服务器(wss://...)。
我不想使用像nginx这样的SSL反向代理。
编辑:以下是代码:
import io.ktor.application.*
import io.ktor.http.cio.websocket.*
import io.ktor.network.tls.certificates.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.websocket.*
import java.io.*
fun main() {
val keyStoreFile = File("build/keystore.jks")
val keystore = generateCertificate(
file = keyStoreFile,
keyAlias = "sampleAlias",
keyPassword = "foobar",
jksPassword = "foobar"
)
val environment = applicationEngineEnvironment {
sslConnector(
keyStore = keystore,
keyAlias = "sampleAlias",
keyStorePassword = { "foobar".toCharArray() },
privateKeyPassword = { "foobar".toCharArray() }) {
port = 8443
keyStorePath = keyStoreFile
}
module(Application::module)
}
embeddedServer(Netty, environment).start(wait = true)
}
private fun Application.module() {
install(WebSockets)
routing {
get("/") { // works at https://localhost:8443 in Firefox after approving cert
call.respondText("This is https")
}
webSocket("/chat") { // fails at wss://localhost:8443/chat in Websocket js client with "Firefox can’t establish a connection to the server"
send("This is wss")
}
}
}