使用 Ktor 在 Kotlin 中创建 WebSocket 应用程序
代码示例: tutorial-server-websockets
使用的插件:Static Content了解如何提供静态内容,例如样式表、脚本、图像等。、 Content NegotiationContentNegotiation 插件有两个主要用途:在客户端和服务器之间协商媒体类型,以及以特定格式序列化/反序列化内容。、Ktor Server 中的 WebSocketsWebSockets 插件允许你在服务器与客户端之间创建多路通信会话。、 kotlinx.serialization
本文将引导您完成使用 Ktor 在 Kotlin 中创建 WebSocket 应用程序的过程。它建立在创建 RESTful API了解如何使用 Kotlin 和 Ktor 构建后端服务,并包含一个生成 JSON 文件的 RESTful API 示例。教程所介绍的内容之上。
本文将介绍如何执行以下操作:
- 创建使用 JSON 序列化的服务。
- 通过 WebSocket 连接发送和接收内容。
- 同时向多个客户端广播内容。
前提条件
您可以独立完成本教程,但我们建议您先完成 创建 RESTful API了解如何使用 Kotlin 和 Ktor 构建后端服务,并包含一个生成 JSON 文件的 RESTful API 示例。 教程,以熟悉 Content NegotiationContentNegotiation 插件有两个主要用途:在客户端和服务器之间协商媒体类型,以及以特定格式序列化/反序列化内容。 和 REST。
我们建议您安装 IntelliJ IDEA,但您也可以使用自选的其他 IDE。
Hello WebSockets
在本教程中,您将在创建 RESTful API了解如何使用 Kotlin 和 Ktor 构建后端服务,并包含一个生成 JSON 文件的 RESTful API 示例。教程中开发的任务管理器服务的基础上,添加通过 WebSocket 连接与客户端交换 Task 对象的能力。为此,您需要添加 WebSockets 插件WebSockets 插件允许你在服务器与客户端之间创建多路通信会话。。虽然您可以手动将其添加到现有项目中,但为了本教程的完整性,您将通过创建一个新项目从头开始。
使用插件创建初始项目
导航至 Ktor Project Generator 。
在 Project artifact 字段中,输入 com.example.ktor-websockets-task-app 作为项目工件的名称。

在插件部分,通过点击 Add 按钮搜索并添加以下插件:
- Content Negotiation
- kotlinx.serialization
- WebSockets
- Static Content

添加插件后,它们将显示在插件部分的右上角。
随后您将看到要添加到项目中的所有插件的列表:

点击 Download 按钮生成并下载您的 Ktor 项目。
添加初始代码
下载完成后,在 IntelliJ IDEA 中打开您的项目,并按照以下步骤操作:
- 导航至 src/main/kotlin 并创建一个名为 model 的新子包。
在 model 包内创建一个新的 Task.kt 文件。
打开 Task.kt 文件,添加一个表示优先级的
enum和一个表示任务的data class:kotlinpackage com.example.model import kotlinx.serialization.Serializable enum class Priority { Low, Medium, High, Vital } @Serializable data class Task( val name: String, val description: String, val priority: Priority )请注意,
Task类使用了来自kotlinx.serialization库的Serializable类型进行注解。这意味着实例可以与 JSON 相互转换,从而允许其内容通过网络进行传输。由于您添加了 WebSockets 插件,生成器已在 src/main/kotlin 中添加了 Websockets.kt 文件,并在 Routing.kt 文件中添加了
webSocket路由。- 打开 Websockets.kt 文件,并将现有的
.configureWebsockets()函数替换为以下内容:kotlinfun Application.configureWebsockets() { install(WebSockets) { contentConverter = KotlinxWebsocketSerializationConverter(Json) pingPeriod = 15.seconds timeout = 15.seconds maxFrameSize = Long.MAX_VALUE masking = false } }- WebSockets 插件已安装并配置了标准设置。
- 设置了
contentConverter属性,使插件能够通过kotlinx.serialization库序列化发送和接收的对象。
打开 Routing.kt 文件,并将现有的
Application.configureRouting()函数替换为以下实现:kotlinfun Application.configureRouting() { routing { webSocket("/tasks") { val tasks = listOf( Task("cleaning", "Clean the house", Priority.Low), Task("gardening", "Mow the lawn", Priority.Medium), Task("shopping", "Buy the groceries", Priority.High), Task("painting", "Paint the fence", Priority.Medium) ) for (task in tasks) { sendSerialized(task) delay(1000.milliseconds) } close(CloseReason(CloseReason.Codes.NORMAL, "All done")) } staticResources("/static", "static") } }- 路由配置了一个单一端点,其相对 URL 为
/tasks。 - 收到请求后,任务列表会通过 WebSocket 连接进行序列化传输。
- 所有条目发送完毕后,服务器关闭连接。
出于演示目的,在发送任务之间引入了 1 秒的延迟。这使您能够观察到任务在客户端中逐步显示。如果没有此延迟,该示例将看起来与前面文章中开发的 RESTful 服务了解如何使用 Kotlin 和 Ktor 构建后端服务,并包含一个生成 JSON 文件的 RESTful API 示例。和 Web 应用程序了解如何使用 Ktor 和 Thymeleaf 模板在 Kotlin 中构建网站。完全相同。
本次迭代的最后一步是为该端点创建一个客户端。由于您包含了 Static Content了解如何提供静态内容,例如样式表、脚本、图像等。 插件,Ktor 项目生成器已在 src/main/resources/static 中添加了一个 index.html 文件。
- 路由配置了一个单一端点,其相对 URL 为
打开 index.html 文件并将现有内容替换为以下代码:
html<html> <head> <title>Using Ktor WebSockets</title> <script> function readAndDisplayAllTasks() { clearTable(); const serverURL = 'ws://0.0.0.0:8080/tasks'; const socket = new WebSocket(serverURL); socket.onopen = logOpenToConsole; socket.onclose = logCloseToConsole; socket.onmessage = readAndDisplayTask; } function readAndDisplayTask(event) { let task = JSON.parse(event.data); logTaskToConsole(task); addTaskToTable(task); } function logTaskToConsole(task) { console.log(`Received ${task.name}`); } function logCloseToConsole() { console.log("Web socket connection closed"); } function logOpenToConsole() { console.log("Web socket connection opened"); } function tableBody() { return document.getElementById("tasksTableBody"); } function clearTable() { tableBody().innerHTML = ""; } function addTaskToTable(task) { tableBody().appendChild(taskRow(task)); } function taskRow(task) { return tr([ td(task.name), td(task.description), td(task.priority) ]); } function tr(children) { const node = document.createElement("tr"); children.forEach(child => node.appendChild(child)); return node; } function td(text) { const node = document.createElement("td"); node.appendChild(document.createTextNode(text)); return node; } </script> </head> <body> <h1>Viewing Tasks Via WebSockets</h1> <form action="javascript:readAndDisplayAllTasks()"> <input type="submit" value="View The Tasks"> </form> <table rules="all"> <thead> <tr> <th>Name</th><th>Description</th><th>Priority</th> </tr> </thead> <tbody id="tasksTableBody"> </tbody> </table> </body> </html>该页面使用了所有现代浏览器均支持的
WebSocket类型。您在 JavaScript 中创建该对象,并将端点的 URL 传入构造函数中。随后,为onopen、onclose和onmessage事件附加事件处理程序。触发onmessage事件后,使用文档对象的方法向表格中追加一行。在 IntelliJ IDEA 中,点击运行按钮 (
) 以启动应用程序。
导航至 http://0.0.0.0:8080/static/index.html。 您应该会看到一个包含按钮和空表格的表单:

当您点击表单上的按钮时,任务会从服务器加载,并以每秒一个的速度显示。因此,表格会逐步填充。您还可以通过打开浏览器Developer Tools中的JavaScript Console来查看记录的消息。

至此,服务按预期正常运行。WebSocket 连接已打开,条目被发送到客户端,随后连接关闭。底层网络虽然存在大量复杂性,但 Ktor 默认处理了所有这些操作。
理解 WebSockets
在进入下一次迭代之前,复习一下 WebSockets 的基础知识可能会有所帮助。 如果您已经熟悉 WebSockets,可以直接继续改进服务的设计。
在之前的教程中,您的客户端一直在发送 HTTP 请求并接收 HTTP 响应。这种机制运行良好,使互联网具备可扩展性和弹性。
但是,它不适用于以下场景:
- 内容随时间逐步生成。
- 内容因事件响应而频繁变化。
- 客户端需要在生成内容时与服务器进行交互。
- 一个客户端发送的数据需要快速传播给其他客户端。
这些场景的示例包括股票交易、购买电影和音乐会门票、在线拍卖竞价以及社交媒体中的聊天功能。WebSockets 正是为处理这些情况而开发的。
WebSocket 连接是通过 TCP 建立的,并且可以持续较长时间。该连接提供全双工通信,这意味着客户端可以同时向服务器发送消息并从服务器接收消息。
WebSocket API 定义了四个事件(open、message、close 和 error)和两个操作(send 和 close)。 在不同的语言和库中,访问此功能的方式可能会有所不同。 例如,在 Kotlin 中,您可以将传入消息序列作为 Flow 来消费。
改进设计
接下来,您将重构现有代码,为更高级的示例做好准备。
在 model 包中,创建一个新的 TaskRepository.kt 文件。
打开 TaskRepository.kt 并添加
TaskRepository类型:kotlinpackage com.example.model object TaskRepository { private val tasks = mutableListOf( Task("cleaning", "Clean the house", Priority.Low), Task("gardening", "Mow the lawn", Priority.Medium), Task("shopping", "Buy the groceries", Priority.High), Task("painting", "Paint the fence", Priority.Medium) ) fun allTasks(): List<Task> = tasks fun tasksByPriority(priority: Priority) = tasks.filter { it.priority == priority } fun taskByName(name: String) = tasks.find { it.name.equals(name, ignoreCase = true) } fun addTask(task: Task) { if (taskByName(task.name) != null) { throw IllegalStateException("Cannot duplicate task names!") } tasks.add(task) } fun removeTask(name: String): Boolean { return tasks.removeIf { it.name == name } } }您可能会记起之前教程中的这段代码。
- 导航至 src/main/kotlin 并打开 Routing.kt 文件。
您现在可以通过利用
TaskRepository来简化Application.configureRouting()中的路由:kotlinrouting { webSocket("/tasks") { for (task in TaskRepository.allTasks()) { sendSerialized(task) delay(1000.milliseconds) } close(CloseReason(CloseReason.Codes.NORMAL, "All done")) } // ... }
通过 WebSockets 发送消息
为了演示 WebSockets 的强大功能,您将创建一个新端点,在该端点中:
- 当客户端启动时,它会接收所有现有的任务。
- 客户端可以创建并发送任务。
- 当一个客户端发送任务时,其他客户端会收到通知。
在 Routing.kt 文件中,将当前的
.configureRouting()方法替换为以下实现:kotlinfun Application.configureRouting() { routing { val sessions = Collections.synchronizedList<WebSocketServerSession>(ArrayList()) webSocket("/tasks") { sendAllTasks() close(CloseReason(CloseReason.Codes.NORMAL, "All done")) } webSocket("/tasks2") { sessions.add(this) sendAllTasks() while(true) { ensureActive() val newTask = receiveDeserialized<Task>() TaskRepository.addTask(newTask) for(session in sessions) { session.sendSerialized(newTask) } } } staticResources("/static", "static") } } private suspend fun DefaultWebSocketServerSession.sendAllTasks() { for (task in TaskRepository.allTasks()) { sendSerialized(task) delay(1000.milliseconds) } }通过这段代码,您完成了以下工作:
- 将发送所有现有任务的功能重构为一个帮助程序方法。
- 在
routing {}块中,创建了一个线程安全的session对象列表,用于跟踪所有客户端。 - 添加了一个相对 URL 为
/tasks2的新端点。当客户端连接到该端点时,相应的session对象会被添加到列表中。随后服务器进入无限循环,等待接收新任务。收到新任务后,服务器将其存储在仓库中,并向所有客户端(包括当前客户端)发送一份副本。
为了测试此功能,您将创建一个新页面来扩展 index.html 中的功能。
在 src/main/resources/static 内创建一个名为 wsClient.html 的新 HTML 文件。
打开 wsClient.html 并添加以下内容:
html<html> <head> <title>WebSocket Client</title> <script> let serverURL; let socket; function setupSocket() { serverURL = 'ws://0.0.0.0:8080/tasks2'; socket = new WebSocket(serverURL); socket.onopen = logOpenToConsole; socket.onclose = logCloseToConsole; socket.onmessage = readAndDisplayTask; } function readAndDisplayTask(event) { let task = JSON.parse(event.data); logTaskToConsole(task); addTaskToTable(task); } function logTaskToConsole(task) { console.log(`Received ${task.name}`); } function logCloseToConsole() { console.log("Web socket connection closed"); } function logOpenToConsole() { console.log("Web socket connection opened"); } function tableBody() { return document.getElementById("tasksTableBody"); } function clearTable() { tableBody().innerHTML = ""; } function addTaskToTable(task) { tableBody().appendChild(taskRow(task)); } function taskRow(task) { return tr([ td(task.name), td(task.description), td(task.priority) ]); } function tr(children) { const node = document.createElement("tr"); children.forEach(child => node.appendChild(child)); return node; } function td(text) { const node = document.createElement("td"); node.appendChild(document.createTextNode(text)); return node; } function getFormValue(name) { return document.forms[0][name].value } function buildTaskFromForm() { return { name: getFormValue("newTaskName"), description: getFormValue("newTaskDescription"), priority: getFormValue("newTaskPriority") } } function logSendingToConsole(data) { console.log("About to send",data); } function sendTaskViaSocket(data) { socket.send(JSON.stringify(data)); } function sendTaskToServer() { let data = buildTaskFromForm(); logSendingToConsole(data); sendTaskViaSocket(data); //prevent form submission return false; } </script> </head> <body onload="setupSocket()"> <h1>Viewing Tasks Via WebSockets</h1> <table rules="all"> <thead> <tr> <th>Name</th><th>Description</th><th>Priority</th> </tr> </thead> <tbody id="tasksTableBody"> </tbody> </table> <div> <h3>Create a new task</h3> <form onsubmit="return sendTaskToServer()"> <div> <label for="newTaskName">Name: </label> <input type="text" id="newTaskName" name="newTaskName" size="10"> </div> <div> <label for="newTaskDescription">Description: </label> <input type="text" id="newTaskDescription" name="newTaskDescription" size="20"> </div> <div> <label for="newTaskPriority">Priority: </label> <select id="newTaskPriority" name="newTaskPriority"> <option name="Low">Low</option> <option name="Medium">Medium</option> <option name="High">High</option> <option name="Vital">Vital</option> </select> </div> <input type="submit"> </form> </div> </body> </html>这个新页面引入了一个 HTML 表单,用户可以在其中输入新任务的信息。提交表单后,将调用
sendTaskToServer()事件处理程序。这会使用表单数据构建一个 JavaScript 对象,并使用 WebSocket 对象的.send()方法将其发送到服务器。在 IntelliJ IDEA 中,点击重新运行按钮(
)以重启应用程序。
要测试此功能,请并排打开两个浏览器并执行以下步骤。
- 在浏览器 A 中,导航至 http://0.0.0.0:8080/static/wsClient.html。您应该会看到显示的默认任务。
- 在浏览器 A 中添加一个新任务。新任务应显示在该页面的表格中。
- 在浏览器 B 中,导航至 http://0.0.0.0:8080/static/wsClient.html。您应该会看到默认任务,以及您在浏览器 A 中添加的所有新任务。
- 在任一浏览器中添加任务。您应该会看到新条目同时出现在两个页面上。

添加自动化测试
为了简化您的 QA 流程并使其快速、可复现且无需人工干预,您可以使用 Ktor 内置的自动化测试支持了解如何使用专用的测试引擎测试您的服务器应用程序。。请按照以下步骤操作:
在 build.gradle.kts 中添加以下依赖项,以便在 Ktor Client 中配置对 Content NegotiationContentNegotiation 插件有两个主要用途:在客户端和服务器之间协商媒体类型,以及以特定格式序列化/反序列化内容。 的支持:
kotlintestImplementation(ktorLibs.client.contentNegotiation)在 IntelliJ IDEA 中,点击编辑器右侧的 Gradle 通知图标 (
) 以加载 Gradle 更改。
导航至 src/test/kotlin 并打开 ServerTest.kt 文件。
将生成的测试类替换为以下实现:
kotlinimport com.example.model.Priority import com.example.model.Task import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.plugins.websocket.DefaultClientWebSocketSession import io.ktor.client.plugins.websocket.WebSockets import io.ktor.client.plugins.websocket.converter import io.ktor.client.plugins.websocket.webSocket import io.ktor.serialization.deserialize import io.ktor.serialization.kotlinx.KotlinxWebsocketSerializationConverter import io.ktor.serialization.kotlinx.json.json import io.ktor.server.testing.testApplication import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.scan import kotlinx.serialization.json.Json import kotlin.test.Test import kotlin.test.assertEquals class ServerTest { @Test fun testRoot() = testApplication { configure() val client = createClient { install(ContentNegotiation) { json() } install(WebSockets) { contentConverter = KotlinxWebsocketSerializationConverter(Json) } } val expectedTasks = listOf( Task("cleaning", "Clean the house", Priority.Low), Task("gardening", "Mow the lawn", Priority.Medium), Task("shopping", "Buy the groceries", Priority.High), Task("painting", "Paint the fence", Priority.Medium) ) var actualTasks = emptyList<Task>() client.webSocket("/tasks") { consumeTasksAsFlow().collect { allTasks -> actualTasks = allTasks } } assertEquals(expectedTasks.size, actualTasks.size) expectedTasks.forEachIndexed { index, task -> assertEquals(task, actualTasks[index]) } } private fun DefaultClientWebSocketSession.consumeTasksAsFlow() = incoming .consumeAsFlow() .map { converter!!.deserialize<Task>(it) } .scan(emptyList<Task>()) { list, task -> list + task } }通过此设置,您:
- 配置您的服务在测试环境中运行,并启用与生产环境中相同的功能,包括 JSON 序列化和 WebSockets。
- 在 Ktor Client了解如何创建和配置 Ktor 客户端。 中配置内容协商和 WebSocket 支持。如果没有这些配置,客户端在使用 WebSocket 连接时将不知道如何将对象(反)序列化为 JSON。
- 声明预期服务返回的
Task列表。 - 使用
client对象的.webSocket函数向/tasks发送请求。 - 将传入的任务作为
Flow消费,逐步将它们添加到列表中。 - 在接收完所有任务后,按照常规方式将
expectedTasks与actualTasks进行比较。
后续步骤
干得不错!通过结合 WebSocket 通信以及使用 Ktor Client 进行自动化测试,您显著增强了任务管理器服务的功能。
继续阅读下一篇教程了解使用 Exposed SQL 库将 Ktor 服务连接到数据库仓库的过程。,探索您的服务如何使用 Exposed 库与关系型数据库无缝交互。
