Skip to content

Instantly share code, notes, and snippets.

@subhanshuja
Last active June 30, 2020 08:14
Show Gist options
  • Save subhanshuja/9079ec9df0927b1da26ee57cf9da1f26 to your computer and use it in GitHub Desktop.
Save subhanshuja/9079ec9df0927b1da26ee57cf9da1f26 to your computer and use it in GitHub Desktop.
Sever Sent Event (SSE)
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)
}
}
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())
}
}
class MessageEventHandler : DefaultEventHandler {
override fun onMessage(event: String, messageEvent: MessageEvent) {
super.onMessage(event, messageEvent)
val data = messageEvent.data
Log.i("message", data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment