Confuse using Library Server Sent Event for Android Client using Nginx Push Stream

微笑、不失礼 提交于 2020-07-06 04:25:03

问题


Our server is used to Nginx as webserver and add compile module of nginx_push_stream. Before used to push stream had used to Restfull then changed to Websocket but websocket sometimes loss when the client or server had small bandwith. At 2019 year, from Websocekt to Server Sent Event (SSE) / event-source such as event stream or text/event-stream to reduce loss both of client or server.

Please anyone have any idea for library event stream is able to use to android client and iPhone client.

I have already used to Okhttp but there is not ready yet used event stream, RxSSE is not able to use in Android no respond at all.

I hope that next year OkHttp is already update OkHttp-EventSource for Android Client also iPhone Client


回答1:


After 3 days, Struggling had search library for supporting SSE of Android client. Then, i found this blog Accessing SSE help me a lot to implementation SSE, also this the library SSE

This sample implementation SSE in kotlin version, even thought library is java version.

1. Preparing for event handler source

interface DefaultEventHandler : EventHandler {

    @Throws(Exception::class)
    override fun onOpen() {
        Log.i("open","open")
    }

    @Throws(Exception::class)
    override fun onClosed() {
        Log.i("close","close")
    }

    @Throws(Exception::class)
    override fun onMessage(event: String, messageEvent: MessageEvent) {
        Log.i("event", messageEvent.data)
    }

    override fun onError(t: Throwable) {
        Log.e("error", t.toString())
    }

    override fun onComment(comment: String) {
        Log.i("event", comment)
    }
}

class MessageEventHandler : DefaultEventHandler {

    override fun onMessage(event: String, messageEvent: MessageEvent) {
        super.onMessage(event, messageEvent)
        val data = messageEvent.data
        Log.i("message", data)
    }
}

2. implementation event source


import java.net.URI
import java.util.concurrent.TimeUnit

.....
 
fun initEventSource(url: String) {
   val eventHandler = MessageEventHandler()

   try {
     val eventSource: EventSource = EventSource.Builder(handler, URI.create(url))
        .reconnectTimeMs(3000)
        .build()
   
      eventSource.start()

      TimeUnit.SECONDS.sleep(10)
   } catch (e: Exception) {
      Log.e("error", e.toString())
   } 
}

I hope this would be alternative method protocol from client to server than used RESTfull or Websocket. When server always sent data to client without need request from client as stream.

I have added a gist of using library SSE https://gist.github.com/subhanshuja/9079ec9df0927b1da26ee57cf9da1f26.



来源:https://stackoverflow.com/questions/58878724/confuse-using-library-server-sent-event-for-android-client-using-nginx-push-stre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!