Akka HTTP supports
server-sent events (SSE) through its streaming capabilities and the
akka.http.scaladsl.model.sse.ServerSentEvent
class. SSE enables efficient real-time communication between a server and clients by pushing updates to clients over a single, long-lived connection.
A use case for employing SSE with Akka HTTP is a live sports score update system. In this scenario, the server continuously sends updated scores and game information to connected clients without requiring them to repeatedly request updates. This reduces latency and improves user experience while minimizing server load.
Example code snippet :
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.sse.ServerSentEvent
import akka.http.scaladsl.server.Directives._
import akka.stream.scaladsl.Source
val route =
path("scores") {
get {
complete {
HttpEntity(
ContentTypes.`text/event-stream`,
Source.fromPublisher(scoreUpdates)
.map(ServerSentEvent(_))
.keepAlive(1.second, () => ServerSentEvent.heartbeat)
)
}
}
}
Http().bindAndHandle(route, "localhost", 8080)?