Last active
June 30, 2020 08:14
-
-
Save subhanshuja/9079ec9df0927b1da26ee57cf9da1f26 to your computer and use it in GitHub Desktop.
Sever Sent Event (SSE)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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