在 Kotlin 中使用 Ktor 建立 WebSocket 應用程式
程式碼範例: tutorial-server-websockets
使用的外掛程式: Static Content了解如何服務靜態內容,例如樣式表、指令碼、圖片等。、 Content NegotiationContentNegotiation 外掛程式有兩個主要用途:在用戶端與伺服器之間協商媒體類型,以及將內容以特定格式進行序列化/反序列化。、WebSockets in Ktor ServerWebsockets 外掛程式允許您在伺服器與用戶端之間建立多向通訊工作階段。、 kotlinx.serialization
本文將引導您完成在 Kotlin 中使用 Ktor 建立 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 外掛程式允許您在伺服器與用戶端之間建立多向通訊工作階段。。雖然您可以手動將其新增至現有專案,但為了本教學的完整性,您將透過建立新專案從頭開始。
建立包含外掛程式的初始專案
在 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 內的 Routing.kt 檔案中新增了 Websockets.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 連線序列化傳送。
- 所有項目傳送完畢後,伺服器會關閉連線。
出於示範目的,在傳送各任務之間引入了一秒鐘的延遲。這讓您可以觀察到任務在用戶端中逐一出現。如果沒有這個延遲,該範例看起來會與先前文章中開發的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事件時,您可以使用 document 物件的方法將資料列附加到表格中。在 IntelliJ IDEA 中,點擊執行按鈕 (
) 以啟動應用程式。
前往 http://0.0.0.0:8080/static/index.html。您應該會看到一個包含按鈕和空白表格的表單:

當您點擊表單時,任務會從伺服器載入,並以每秒一個的速率顯示。因此,表格會逐步填入內容。您也可以透過開啟瀏覽器開發人員工具中的 JavaScript 主控台 來檢視記錄的訊息。

至此,該服務運作符合預期。WebSocket 連線已開啟,項目已傳送至用戶端,然後連線關閉。底層網路雖然十分複雜,但 Ktor 預設會處理這一切。
了解 WebSockets
在進入下一個迭代之前,回顧 WebSockets 的一些基礎知識可能會有所幫助。如果您已經熟悉 WebSockets,可以直接跳至改善服務的設計。
在先前的教學中,您的用戶端傳送 HTTP 請求並接收 HTTP 回應。這種方式運作良好,使網際網路具備可擴充性與韌性。
但是,它不適用於以下情境:
- 內容隨時間逐步產生。
- 內容因應事件頻繁變更。
- 用戶端需要在內容產生時與伺服器互動。
- 某個用戶端傳送的資料需要快速傳播給其他用戶端。
這些情境的範例包括股票交易、購買電影院和演唱會門票、線上拍賣競標,以及社群媒體中的聊天功能。WebSockets 正是為了處理這些情況而開發的。
WebSocket 連線是透過 TCP 建立的,並且可以持續很長一段時間。該連線提供全雙工通訊 (full duplex communication),這表示用戶端可以同時向伺服器傳送訊息並接收來自伺服器的訊息。
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。
- 宣告您預期服務傳回的
Tasks清單。 - 使用
client物件的.webSocket函式向/tasks傳送請求。 - 將傳入的任務作為
Flow取用,逐步將它們新增至清單中。 - 接收所有任務後,依照慣用方式將
expectedTasks與actualTasks進行比對。
後續步驟
做得好!透過整合 WebSocket 通訊以及搭配 Ktor Client 的自動化測試,您已顯著增強了任務管理器服務的功能。
繼續閱讀 下一篇教學了解使用 Exposed SQL 程式庫將 Ktor 服務連接到資料庫存儲庫的過程。,探索您的服務如何使用 Exposed 程式庫與關聯式資料庫無縫互動。
