java.net.MalformedURLException: unknown protocol: ws KTOR android

864 views Asked by At

as stated in documentation I want to create websocket in Server and connect to it from Android my code for Android:

 class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val client = HttpClient {
        install(WebSockets)
    }
    lifecycleScope.launchWhenCreated {
        withContext(Dispatchers.IO) {
            client.ws(
                    method = HttpMethod.Get,
                    host = "ws://192.168.43.4",
                    port = 23569, path = ""
            ) { // this: DefaultClientWebSocketSession

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

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

             

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

}

}

but it gives the following error:

 java.net.MalformedURLException: unknown protocol: ws
    at java.net.URL.<init>(URL.java:597)
    at java.net.URL.<init>(URL.java:487)
    at java.net.URL.<init>(URL.java:436)
    at io.ktor.client.engine.android.AndroidClientEngine.getProxyAwareConnection(AndroidClientEngine.kt:102)
    at io.ktor.client.engine.android.AndroidClientEngine.execute(AndroidClientEngine.kt:47)
    at io.ktor.client.engine.HttpClientEngine$executeWithinCallContext$2.invokeSuspend(HttpClientEngine.kt:86)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
1

There are 1 answers

0
Sergey Mashkov On BEST ANSWER

The Android engine doesn't support WebSockets. Please use other engines like CIO or OkHttp.