Kotlin下OkHttp WebSocket客户端简单用法


OkHttp provides convenient way to create a WebSocket client. We can send and receive messages from and to a WebSocket server. But there are some notable problems

Use OkHttp

It is simple. Open your project level build.gradle file and add following codes in the dependencies section.

implementation 'com.squareup.okhttp3:okhttp:3.11.0'

Don’t forget to add INTERNET permission in AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="..." >

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



Create WebSocket Client

We need to build a request with a WebSocket url, such as “ws://…” or “was://…”. Next, get a OkHttpClient and new a WebSocket connection with the previous request and a listener, WebSocketListener().

val request = Request.Builder().url(YOUR_WS_PATH).build()

val webSocket = OkHttpClient().newWebSocket(request, object WebSocketListener() {...})

In the WebSocketListener(), we can override onOpen(), onMessage(), onFailure(), onClosed() and so on to trigger desired logics.

Then, An Exception Occurs ?!

All functions in WebSocketListener() are called in a background thread.

OkHttp use an async call to deal a WebSocket connect to prevent blocking main thread. Therefore, if you call functions doing UI related logics after receiving some specific messages, an exception will occur and your application maybe crash at that moment. You can simply use a Handler() or RxJava skills to back to UI thread.

val handler = Handler()
override() fun onMessage(...) {



邮箱地址不会被公开。 必填项已用*标注