Skip to content

Instantly share code, notes, and snippets.

@kamilkloch
Created July 12, 2023 11:52
Show Gist options
  • Save kamilkloch/912a504ab27cb47d38068255be8c7e4b to your computer and use it in GitHub Desktop.
Save kamilkloch/912a504ab27cb47d38068255be8c7e4b to your computer and use it in GitHub Desktop.
http4s blaze vs ember websocket server
import cats.effect.{IO, IOApp}
import fs2.Stream
import org.http4s.blaze.server.BlazeServerBuilder
import org.http4s.ember.server.EmberServerBuilder
import org.http4s.server.Router
import sttp.capabilities.fs2.Fs2Streams
import sttp.tapir._
import com.comcast.ip4s._
import sttp.tapir.server.http4s.Http4sServerInterpreter
import scala.concurrent.duration.DurationInt
object TapirWebSocketServer extends IOApp.Simple {
private val wsEndpoint = endpoint.get
.in("ts")
.out(webSocketBody[Long, CodecFormat.TextPlain, Long, CodecFormat.TextPlain](Fs2Streams[IO]))
private val responseStream = Stream.repeatEval(IO.realTime.map(_.toMillis).delayBy(500.millis))
private val wsRoutes = Http4sServerInterpreter[IO]().toWebSocketRoutes(wsEndpoint.serverLogicSuccess(_ => IO.pure((_: Stream[IO, Long]) => responseStream)))
private val connectorPoolSize = Math.max(2, Runtime.getRuntime.availableProcessors() / 8)
override protected def computeWorkerThreadCount: Int =
Math.max(2, super.computeWorkerThreadCount / 2)
val blaze = BlazeServerBuilder[IO]
.bindHttp(8888, "0.0.0.0")
.withMaxConnections(65536)
.withConnectorPoolSize(connectorPoolSize)
.withHttpWebSocketApp(wsb => Router("/" -> wsRoutes(wsb)).orNotFound)
.resource
.useForever
val ember = EmberServerBuilder.default[IO]
.withPort(port"8888")
.withHost(host"0.0.0.0")
.withMaxConnections(65536)
.withHttpWebSocketApp(wsb => Router("/" -> wsRoutes(wsb)).orNotFound)
.build
.useForever
def run: IO[Unit] = blaze
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment