WebSockets

预计阅读时间:1分钟

该功能在工件io.ktor.client.features.websocket.WebSockets中的io.ktor:ktor-client-websockets:$ktor_version,io.ktor:ktor-client-cio:$ktor_version,io.ktor:ktor-client-js:$ktor_version,io.ktor:ktor-client-okhttp:$ktor_version类中定义io.ktor:ktor-client-websockets:$ktor_version,io.ktor:ktor-client-cio:$ktor_version,io.ktor:ktor-client-js:$ktor_version,io.ktor:ktor-client-okhttp:$ktor_version .
dependencies { implementation "io.ktor:ktor-client-websockets:$ktor_version" implementation "io.ktor:ktor-client-cio:$ktor_version" implementation "io.ktor:ktor-client-js:$ktor_version" implementation "io.ktor:ktor-client-okhttp:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-websockets:$ktor_version") implementation("io.ktor:ktor-client-cio:$ktor_version") implementation("io.ktor:ktor-client-js:$ktor_version") implementation("io.ktor:ktor-client-okhttp:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-websockets</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-websockets</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-websockets</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-websockets</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Ktor为以下引擎提供WebSocket客户端:CIO,OkHttp,Js. 要获取有关服务器端的更多信息,请遵循本 .

连接后,客户端和服务器WebSocket共享相同的WebSocketSession接口进行通信.

创建支持WebSocket的HTTP客户端的基本用法非常简单:

val client = HttpClient {
    install(WebSockets)
}

创建完成后,我们可以执行一个请求,启动一个WebSocketSession

client.ws(
    method = HttpMethod.Get,
    host = "127.0.0.1",
    port = 8080, path = "/route/path/to/ws"
) { // this: DefaultClientWebSocketSession

    // Send text frame.
    send("Hello, Text frame")

    // Send text frame.
    send(Frame.Text("Hello World"))

    // Send binary frame.
    send(Frame.Binary(...))

    // Receive frame.
    val frame = incoming.receive()
    when (frame) {
        is Frame.Text -> println(frame.readText())
        is Frame.Binary -> println(frame.readBytes())
    }
}

有关WebSocketSession的更多信息,请检查WebSocketSession页面API参考 .

by  ICOPY.SITE