Ktor Server 中的 WebSockets 序列化
與 ContentNegotiation 外掛程式類似,WebSockets 允許您以特定的格式序列化/反序列化文字訊框(text frame)。Ktor 開箱即用支援以下格式:JSON、XML、CBOR 和 ProtoBuf。
新增相依性
在使用 kotlinx.serialization 轉換器之前,您需要按照 安裝 章節所述新增 Kotlin 序列化外掛程式。
JSON
要序列化/反序列化 JSON 資料,您可以選擇以下其中一個程式庫:kotlinx.serialization、Gson 或 Jackson。
在組建指令碼中新增 ktor-serialization-kotlinx-json 構件:
在組建指令碼中新增 ktor-serialization-gson 構件:
在組建指令碼中新增 ktor-serialization-jackson 構件:
XML
要序列化/反序列化 XML,請在組建指令碼中新增 ktor-serialization-kotlinx-xml:
請注意,XML 序列化 在
jsNode目標上不受支援。
CBOR
要序列化/反序列化 CBOR,請在組建指令碼中新增 ktor-serialization-kotlinx-cbor:
ProtoBuf
要序列化/反序列化 ProtoBuf,請在組建指令碼中新增 ktor-serialization-kotlinx-protobuf:
設定序列化程式
JSON 序列化程式
要在 WebSockets 配置 中註冊 JSON 序列化程式,請建立一個帶有 Json 參數的 KotlinxWebsocketSerializationConverter 執行個體,並將此執行個體指派給 contentConverter 屬性:
import io.ktor.serialization.kotlinx.*
import kotlinx.serialization.json.*
install(WebSockets) {
contentConverter = KotlinxWebsocketSerializationConverter(Json)
}要註冊 Gson 序列化程式,請將 GsonWebsocketContentConverter 指派給 contentConverter 屬性:
import io.ktor.serialization.gson.*
install(WebSockets) {
contentConverter = GsonWebsocketContentConverter()
}要註冊 Jackson 序列化程式,請將 JacksonWebsocketContentConverter 指派給 contentConverter 屬性:
import io.ktor.serialization.jackson.*
install(WebSockets) {
contentConverter = JacksonWebsocketContentConverter()
}XML 序列化程式
要在 WebSockets 配置 中註冊 XML 序列化程式,請建立一個帶有 XML 參數的 KotlinxWebsocketSerializationConverter 執行個體,並將此執行個體指派給 contentConverter 屬性:
import nl.adaptivity.xmlutil.serialization.*
install(WebSockets) {
contentConverter = KotlinxWebsocketSerializationConverter(XML)
}CBOR 序列化程式
要在 WebSockets 配置 中註冊 CBOR 序列化程式,請建立一個帶有 Cbor 參數的 KotlinxWebsocketSerializationConverter 執行個體,並將此執行個體指派給 contentConverter 屬性:
import io.ktor.serialization.kotlinx.cbor.*
install(WebSockets) {
contentConverter = KotlinxWebsocketSerializationConverter(Cbor)
}ProtoBuf 序列化程式
要在 WebSockets 配置 中註冊 ProtoBuf 序列化程式,請建立一個帶有 ProtoBuf 參數的 KotlinxWebsocketSerializationConverter 執行個體,並將此執行個體指派給 contentConverter 屬性:
import kotlinx.serialization.protobuf.*
install(WebSockets) {
contentConverter = KotlinxWebsocketSerializationConverter(ProtoBuf)
}接收與傳送資料
建立資料類別
要將訊框序列化/反序列化為物件,您需要建立一個資料類別,例如:
data class Customer(val id: Int, val firstName: String, val lastName: String)如果您使用 kotlinx.serialization,請確保該類別具有 @Serializable 註解:
@Serializable
data class Customer(val id: Int, val firstName: String, val lastName: String)接收資料
要接收並轉換文字訊框的內容,請呼叫接受資料類別作為參數的 receiveDeserialized 函式:
webSocket("/customer") {
val customer = receiveDeserialized<Customer>()
println("A customer with id ${customer.id} is received by the server.")
}要從 傳入 通道接收反序列化的訊框,請使用 WebsocketContentConverter.deserialize 函式。WebsocketContentConverter 可透過 WebSocketServerSession.converter 屬性取得。
傳送資料
要使用 指定的格式 在文字訊框中傳遞資料物件,您可以使用 sendSerialized 函式:
webSocket("/customer/1") {
sendSerialized(Customer(1, "Jane", "Smith"))
}您可以在此處找到完整的範例:server-websockets-serialization。
