OKHttp对WebSocket的支持
1.1、使用要求
1.2、在build.gradle里面添加依赖
dependencies {
    compile 'com.squareup.okhttp3:okhttp:3.7.0'
}

具体的版本号,请查看OKHttp在GitHub上的网址

1.3、使用示例

1、创建一个OkHttpClient的实例:

val okHttpClient = OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)//设置链接超时时间
    .readTimeout(10, TimeUnit.SECONDS)   //设置读取超时时间
    .writeTimeout(10, TimeUnit.SECONDS)  //设置写入超时时间
    .pingInterval(3000, TimeUnit.MILLISECONDS)
    .retryOnConnectionFailure(true)
    .build()

2、创建一个Request的实例:

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

3、创建一个WebSocketListener的实例:

val webSocketListener = object : WebSocketListener() {

    override fun onOpen(webSocket: WebSocket, response: Response) {
        Logger.i(TAG, "onOpen() ${response.code()}")
    }

    override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
        Logger.i(TAG, "onClosing()")
    }

    override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
        Logger.i(TAG, "onClosed() code = $code, reason = $reason")
    }

    override fun onFailure(webSocket: WebSocket, e: Throwable, response: Response?) {
        Logger.e(TAG, "onFailure()", e)
    }

    override fun onMessage(webSocket: WebSocket, text: String) {
        Logger.i(TAG, "onMessage() text = $text")
    }

    override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
        Logger.i(TAG, "onMessage() bytes = ${bytes.hex()}")
    }
}

4、启动连接:

val webSocket = okHttpClient.newWebSocket(request, webSocketListener)