ktor icon indicating copy to clipboard operation
ktor copied to clipboard

Websocket CIO engine receive channel may close instantly

Open XuaTheGrate opened this issue 4 years ago • 4 comments

Ktor Version and Engine Used (client or server and name) Kotlin 1.3.72 Ktor: 1.3.2 Engine: CIO (Client) Websockets, Kotlinx.Serialization

Describe the bug Websocket receive channel may close instantly: Exception in thread "DefaultDispatcher-worker-3" kotlinx.coroutines.channels.ClosedReceiveChannelException: Channel was closed Other times it works as expected

To Reproduce Run the following:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.wss
import io.ktor.http.cio.websocket.*
import kotlinx.coroutines.*
import java.nio.charset.Charset

fun main(args: Array<String>) = runBlocking {
    val client = HttpClient(CIO) {
        install(WebSockets)
    }
    client.wss("wss://echo.websocket.org") {
        GlobalScope.launch {
            while (true) {
                val msg = incoming.receive()
                println(msg.readBytes().toString(Charset.forName("UTF-8")))
            }
        }
        send("Hello, world")
        send("jadshf")
        send("47y3th")
        close(CloseReason(1000, "OK"))
    }
}

Expected behavior For it to print the three messages before crashing.

Screenshots Sometimes works as expected: goodoutput Sometimes it doesn't: badoutput

XuaTheGrate avatar May 08 '20 02:05 XuaTheGrate

Hi @XuaTheGrate, thanks for the report. Could you post the output as a text here? Image links show 404 for me.

Btw, Full stack trace would be nice too.

e5l avatar May 12 '20 07:05 e5l

My apologies, the host I had been using reset recently. Here is what the images had shown: image

I did determine that the issue was with the server (not written in Kotlin), however I believe a more appropriate error should be raised, or a CloseReason should be defined.

XuaTheGrate avatar May 13 '20 23:05 XuaTheGrate

Please check the following ticket on YouTrack for follow-ups to this issue. GitHub issues will be closed in the coming weeks.

oleg-larshin avatar Aug 10 '20 15:08 oleg-larshin

@XuaTheGrate could you give any more info on your problem/solution? I'm experiencing the same issue in a very simple WS setup with CIO

CluEleSsUK avatar Feb 23 '22 10:02 CluEleSsUK