Created
November 3, 2016 11:22
-
-
Save rpless/77d995c3f41c59c3d58094f7880bdb70 to your computer and use it in GitHub Desktop.
An example of using sse in Finch on my WIP branch
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
package io.finch.sse | |
import java.nio.charset.Charset | |
import cats.Show | |
import com.twitter.concurrent.AsyncStream | |
import com.twitter.conversions.time._ | |
import com.twitter.finagle.Http | |
import com.twitter.finagle.http.Response | |
import com.twitter.io.Buf | |
import com.twitter.util.{Future, JavaTimer} | |
import io.finch._ | |
import io.finch.internal.BufText | |
case class Example(x: Int) | |
object Example { | |
implicit val show: Show[Example] = Show.fromToString | |
} | |
object Main { | |
import Example._ | |
import ServerSentEvent._ | |
val file = | |
""" | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
</head> | |
<body> | |
<script> | |
var source = new EventSource('/sse'); | |
source.onmessage = function(e) { | |
document.body.innerHTML += e.data + '<br>'; | |
}; | |
</script> | |
</body> | |
</html> | |
""" | |
val index: Endpoint[Response] = get(/)({ | |
val response = Response() | |
response.content = Buf.Utf8(file) | |
response.contentType = "text/html" | |
response | |
}) | |
val random = new scala.util.Random | |
implicit val timer = new JavaTimer | |
def ints(): EventStream[Example] = { | |
ServerSentEvent(Example(random.nextInt)) +:: | |
AsyncStream.fromFuture(Future.sleep(1000.millis)).flatMap(_ => ints()) | |
} | |
val sse: Endpoint[EventStream[Example]] = get("sse")(ServerSentEvent.stream(ints())) | |
def main(args: Array[String]): Unit = Http.server.serve(":8081", (sse :+: index).toServiceAs[Text.EventStream]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment