question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

ktor websocket client crashes with java.io.IOException: Software caused connection in Android abort

See original GitHub issue

Version: 1.2.2, client, io.ktor:ktor-client-cio, io.ktor:ktor-client-websockets Android 7.0

When using websocket client

To Reproduce code:

val uri = URLBuilder().takeFrom(configuration.url).build()
val httpClientEngine = CIO.create { }
val client = HttpClient(httpClientEngine).config {
    install(WebSockets)
}

suspend fun process(session: DefaultClientWebSocketSession): ConnectionStatus {
            while (session.isActive && !session.closeReason.isCompleted) {
                try {
                    select<Unit> {
                         session.incoming.onReceiveOrNull { frame ->
                            when (frame) {
                                null -> { // channel has been closed
                                    println("closed")
                                    session.close()
                                }
                                else -> Unit
                            }
                        }
                    }
                } catch (e: IOException) {
                    println("io exception: ${e}")
                    session.close()
                } catch (e: Throwable) {
                    println("exception: ${e}")
                    session.close()
                }
            }
}
runBlocking {
  try {
    when (uri.protocol.isSecure()) {
        true -> client.wss(host = uri.host, port = uri.port, path = uri.encodedPath) { process(this) }
        false -> client.ws(host = uri.host, port = uri.port, path = uri.encodedPath) { process(this) }
    }
  } catch (ex: Exception) {
    println("catched: ${ex}")
  }
}
  1. Start code with internet enabled and with some websocket url
  2. disconnect internet IOException will be thrown, but not caught anywhere.

Expected behavior I’m expecting that this IOException won’t leak and can be caught by try/catch.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:7
  • Comments:16 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
antanas-arvaseviciuscommented, Jul 18, 2019

Investigation history:

maybe problem is here: Socket.tls(coroutineContext: CoroutineContext, config: TLSConfig) function:

  1. calls val reader = openReadChannel()
  2. which calls attachForReading(channel: ByteChannel): WriterJob
  3. which calls CoroutineScope.attachForReadingDirectImpl(...) // <— this is implemented in internal abstract class NIOSocketImpl<out S> with CoroutineScope
  4. which call writer(Dispatchers.Unconfined, channel) { .. block .. }
  5. and it this block there is “val rc = nioChannel.read(buffer)” <<- which throws that IOException code:
internal abstract class NIOSocketImpl<out S> implements CoroutineScope:

    override val socketContext: CompletableJob = Job()

    override val coroutineContext: CoroutineContext
        get() = socketContext
  1. and attachForReadingDirectImpl() is called on this coroutineScope which is just Job() without any specified dispatchers nor any parent contexts, so this scope is not bound to any of coroutines nor callees of tls() nor ktor CIO context, this just runs on Dispatchers.Default with Job() So there is no way to catch this exception and its bubbled to global exception handler.
  2. app fatally crashes.
1reaction
antanas-arvaseviciuscommented, Jan 13, 2020

We are still waiting while ktor team will fix this critical bug which was introduced in some versions later and never got fixed. This bug cause crashes not only android but also server side thus making multiplatform websockets unusable.

On 2020-01-12, Sun at 21:03, David Alan Cohen notifications@github.com wrote:

This may not be applicable to every application that is running into this issue, but if you want to swallow this IOException so that the app doesn’t fatally crash, you can override the thread’s default exception handler with custom behavior using Thread.setDefaultUncaughtExceptionHandler() in MainActivity.onCreate().

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/ktorio/ktor/issues/1237?email_source=notifications&email_token=ABABZHB4WLWQTOXJYYMJIEDQ5OATVA5CNFSM4IE3THVKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEIXEEXI#issuecomment-573456989, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABABZHFP2WXR3BCG2OYPRVLQ5OATVANCNFSM4IE3THVA .

Read more comments on GitHub >

github_iconTop Results From Across the Web

Ktor-client OkHttp exceptions crash Android app
I have java.net.SocketException: Software caused connection abort in a following scenario: Start streaming with client.get<HttpStatement>(url).
Read more >
[Solved]-Ktor Android Client Websocket Connection Failed-kotlin
Coding example for the question Ktor Android Client Websocket Connection Failed-kotlin. ... val client = HttpClient(CIO) { install(WebSockets) } client.
Read more >
WhatsNew 1.6 | Ktor Framework
Android : SocketException: Software caused connection abort - for every consecutive call after it failed in the streaming once.
Read more >
Software caused connection abort' in java server - Stack ...
Where are you starting the server from? · I'm starting it from an Activity · @UmangMathur Have you try testing with personal wifi...
Read more >
How to Fix with java.net.SocketException: Connection reset ...
This occurred when Server closed the connection, while the client is still waiting to read data from its InputStream. For example, if you...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found