Android 使用sse实现长连接的效果

import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.internal.sse.RealEventSource
import okhttp3.sse.EventSourceListener
import java.util.concurrent.TimeUnit

class SseManager {
    private var httpClient: OkHttpClient
    private var eventSource: RealEventSource? = null

    init {
        httpClient = OkHttpClient()
    }

    fun startListening(url: String, listener: EventSourceListener) {
        val request: Request = Request.Builder()
            .url(url)
            .build()
        httpClient = OkHttpClient.Builder()
            .connectTimeout(1, TimeUnit.DAYS)
            .readTimeout(1, TimeUnit.DAYS) //这边需要将超时显示设置长一点,不然刚连上就断开,之前以为调用方式错误被坑了半天
            .build()

        eventSource = RealEventSource(request, listener)
        eventSource?.connect(httpClient)
    }

    fun stopListening() {
        eventSource?.cancel()
    }
}
import com.hanweb.android.complat.JLog
import okhttp3.Response
import okhttp3.sse

你可能感兴趣的:(android)