Search code examples
androidkotlinwebsocketktor-client

Ktor client websocket connection timeout when using wifi


I am using Ktor Client to establish a websocket connection in an Android App. The connection works fine on the emulator and even on a smartphone when using mobile data. The problem starts occurring when using wifi. When wifi is enabled on a smartphone, normal HTTP requests over Ktor Client keep working, but the websocket connection fails with a timeout exception:

REQUEST wss://xxx failed with exception: io.ktor.network.sockets.ConnectTimeoutException: Connect timeout has expired [url=wss://xxx, connect_timeout=unknown ms]

My code is as following:

override suspend fun initSession(userId: Int): Resource<Unit> {
    return try {
        socket = client.webSocketSession {
            url(CallSocketService.Endpoints.Base.url + "/$userId")
        }
        if(socket?.isActive == true) {
            Resource.Success(Unit)
        } else Resource.Error("Couldn't establish connection")
    } catch (e: Exception) {
        e.printStackTrace()
        Resource.Error(e.localizedMessage ?: "Unknown Error")
    }
}

My manifest contains internet permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

The problem was tested on multiple devices in multiple wifi networks. The Ktor Client version for all components is 1.6.7.

I really have no idea why the websocket only fails on wifi. Looking forward to someone that knows more.

Thanks in advance!


Solution

  • The problem seems to be DNS related. I have opened a bugreport on youtrack where I describe the problem and the solution: https://youtrack.jetbrains.com/issue/KTOR-3932

    As of the day of writing, there is currently no solution for Ktor, but OkHttp is able to solve this problem.