Skip to content

Commit ff4e1da

Browse files
committed
KTOR-9639 Darwin: WebSocket crashes when a frame arrives after the session is closed
1 parent 7763c0a commit ff4e1da

1 file changed

Lines changed: 7 additions & 9 deletions

File tree

ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinWebsocketSession.kt

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,13 @@ internal class DarwinWebsocketSession(
7070
launch {
7171
sendMessages()
7272
}
73-
coroutineContext[Job]!!.invokeOnCompletion { cause ->
74-
if (cause != null) {
73+
coroutineContext.job.invokeOnCompletion { cause ->
74+
if (cause != null && cause !is CancellationException) {
7575
val code = CloseReason.Codes.INTERNAL_ERROR.code.convert<NSInteger>()
7676
task.cancelWithCloseCode(code, "Client failed".toByteArray().toNSData())
7777
}
7878
_incoming.close(cause)
79-
_outgoing.cancel(cause = CancellationException(cause))
79+
_outgoing.cancel(cause = cause as? CancellationException ?: CancellationException(cause))
8080
}
8181
}
8282

@@ -98,12 +98,10 @@ internal class DarwinWebsocketSession(
9898

9999
private fun receiveFrame(frame: Frame) {
100100
val result = _incoming.trySend(frame)
101-
when {
102-
result.isSuccess -> return
103-
result.isClosed -> result.exceptionOrNull()?.let { throw it }
104-
else -> launch(start = CoroutineStart.UNDISPATCHED) {
105-
_incoming.send(frame)
106-
}
101+
if (result.isSuccess || result.isClosed) return
102+
103+
launch(start = CoroutineStart.UNDISPATCHED) {
104+
_incoming.send(frame)
107105
}
108106
}
109107

0 commit comments

Comments
 (0)