How to Talk STOMP over WebSocket
In this guide, we make a ZIO HTTP client and a ZIO HTTP server talk STOMP over a WebSocket with the zio-http-stomp module. By the end, the client connects, subscribes to the destination /topic/greetings, sends one message to it, receives that message back from the server, and disconnects.
We start by building STOMP frames and putting them into WebSocket messages. Then we write a small STOMP endpoint for the client to talk to, write the client, and run the two together. The last section shows how to read STOMP frames that arrive as WebSocket text messages.
The Problem
STOMP is a text protocol: every frame is a command line, one key:value line per header, an empty line, a body, and a NUL byte. A WebSocket only carries the messages; it knows nothing about frames. Without a STOMP library, the client writes each frame as a string by hand and takes apart every frame it receives.
For example, a client that sends a message and reads the destination of the reply looks like this:
import zio._
import zio.http._
val NUL = '\u0000'
val sendText =
"SEND\ndestination:/topic/greetings\ncontent-type:text/plain\ncontent-length:13\n\nHello, STOMP!" + NUL
def command(text: String): String =
text.takeWhile(_ != '\n')
def header(text: String, key: String): Option[String] =
text.takeWhile(_ != NUL).split("\n\n", 2).head.split("\n").drop(1).collectFirst {
case line if line.startsWith(key + ":") => line.drop(key.length + 1)
}
val client: WebSocketApp[Any] =
Handler.webSocket { channel =>
channel.receiveAll {
case ChannelEvent.Read(WebSocketFrame.Text(text)) if command(text) == "MESSAGE" =>
ZIO.debug(header(text, "destination"))
case ChannelEvent.UserEventTriggered(ChannelEvent.UserEvent.HandshakeComplete) =>
channel.send(ChannelEvent.Read(WebSocketFrame.text(sendText)))
case _ =>
ZIO.unit
}
}
Every frame the client sends is a string that the compiler cannot check: a missing newline, a wrong content-length, or a forgotten NUL byte only shows up when the server rejects the frame. Every frame it receives goes through string parsing that leaves escaped characters in header values, such as \c for a colon, as they are.
The zio-http-stomp module models a frame as a StompFrame value with a command, headers, and a body, builds the frames of every STOMP command, and turns frames into WebSocket messages and back.
Prerequisites
zio-http-stomp is a separate module, published next to zio-http:
libraryDependencies += "dev.zio" %% "zio-http-stomp" % "3.12.0"
All examples use these imports. zio.http.stomp._ brings the STOMP types and the extension methods that turn frames into WebSocket messages and back:
import zio._
import zio.http._
import zio.http.stomp._
This guide assumes you know how to write a WebSocket handler with Handler.webSocket and how to serve routes. If not, start with Socket and WebSocketFrame.
Building STOMP Frames
Each STOMP command has a constructor on the StompFrame companion object. Our client needs three of them: connect opens the STOMP session, subscribe asks for the messages of a destination, and send sends a message to a destination:
val connectFrame: StompFrame =
StompFrame.connect(host = "localhost")
val subscribeFrame: StompFrame =
StompFrame.subscribe(destination = "/topic/greetings", id = "sub-0")
val sendFrame: StompFrame =
StompFrame.send("/topic/greetings", "Hello, STOMP!", Some("text/plain"), Map.empty[String, String])
connect asks for STOMP 1.2 by default, and subscribe uses the acknowledgement mode auto by default. The id of a subscription is chosen by the client; the server puts it into every message it delivers for that subscription. The send constructor that takes the body as a String has no default arguments, so the content type and the extra headers are always passed; the constructor that takes a Chunk[Byte] has defaults for both.
encode turns a frame into the bytes that go over the wire. Printing them, with the NUL byte shown as ^@, shows the layout of a frame:
println(sendFrame.encode.asString(Charsets.Utf8).replace("\u0000", "^@"))
// SEND
// destination:/topic/greetings
// content-type:text/plain
// content-length:13
//
// Hello, STOMP!^@
send sets the content-length header from the body, so the frame is complete without any header written by hand.
Carrying STOMP Frames in WebSocket Messages
toWebSocketFrame wraps the encoded bytes of a StompFrame in a WebSocket binary frame, and asStompFrame decodes a WebSocket frame back into a StompFrame. Sending a STOMP frame on a WebSocket channel is then one call:
def sendStomp(channel: WebSocketChannel, frame: StompFrame): Task[Unit] =
channel.send(ChannelEvent.Read(frame.toWebSocketFrame))
asStompFrame returns an effect that fails when the WebSocket frame does not hold a STOMP frame:
val roundTrip: Task[StompFrame] =
connectFrame.toWebSocketFrame.asStompFrame
val fromText: Task[StompFrame] =
WebSocketFrame.text("CONNECT\nhost:localhost\n\n\u0000").asStompFrame
roundTrip succeeds with the original CONNECT frame. fromText fails with IllegalArgumentException: STOMP frames must be transmitted as WebSocket binary frames: the module sends STOMP frames as binary WebSocket messages and reads them only from binary messages. A peer that uses text messages needs the conversion shown in Talking to a Peer That Sends Text Frames.
Serving a STOMP Endpoint
The client needs a server that speaks STOMP. zio-http-stomp has no message broker, so we write a small STOMP endpoint as a WebSocket handler. For each connection, it keeps the subscriptions of that connection in a Ref, from destination to subscription id, and answers four commands:
CONNECT: replies with aCONNECTEDframe.SUBSCRIBE: records the subscription.SEND: delivers the body as aMESSAGEframe to the subscription for that destination, if there is one.DISCONNECT: replies with aRECEIPTframe when the client asked for a receipt.
val stompServer: WebSocketApp[Any] =
Handler.webSocket { channel =>
Ref.make(Map.empty[String, String]).flatMap { subscriptions =>
channel.receiveAll {
case ChannelEvent.Read(frame: WebSocketFrame.Binary) =>
frame.asStompFrame.flatMap { stomp =>
stomp.command match {
case StompCommand.Connect =>
sendStomp(channel, StompFrame.connected(session = Some("session-1")))
case StompCommand.Subscribe =>
val destination = stomp.header("destination").getOrElse("")
val id = stomp.header("id").getOrElse("")
subscriptions.update(_ + (destination -> id))
case StompCommand.Send =>
val destination = stomp.header("destination").getOrElse("")
subscriptions.get.flatMap { subs =>
ZIO.foreachDiscard(subs.get(destination)) { subscriptionId =>
Random.nextUUID.flatMap { messageId =>
sendStomp(
channel,
StompFrame.message(
destination = destination,
messageId = messageId.toString,
subscription = subscriptionId,
body = stomp.body.getOrElse(Chunk.empty),
contentType = stomp.header("content-type"),
),
)
}
}
}
case StompCommand.Disconnect =>
ZIO.foreachDiscard(stomp.header("receipt")) { receiptId =>
sendStomp(channel, StompFrame.receipt(receiptId))
}
case _ =>
ZIO.unit
}
}
case _ =>
ZIO.unit
}
}
}
val routes: Routes[Any, Response] =
Routes(Method.GET / "stomp" -> handler(stompServer.toResponse))
Frames on one WebSocket arrive in order and receiveAll handles them one at a time, so a SUBSCRIBE is recorded before the SEND that follows it is handled. When asStompFrame fails, the handler fails and the connection closes.
This endpoint only delivers a message to subscriptions of the connection that sent it. A broker that serves many clients keeps its subscriptions outside the connections, for example in a Hub per destination, and delivers each message to every subscriber.
Writing the STOMP Client
The client is a WebSocket handler too. It reacts to the events of its connection in order:
- When the WebSocket handshake is complete, it sends
CONNECT. - When
CONNECTEDarrives, it subscribes to/topic/greetingsand sendsHello, STOMP!there. - When the
MESSAGEarrives, it hands the frame to the program through aPromiseand sendsDISCONNECTwith a receiptid. - When the
RECEIPTarrives, the server has seen theDISCONNECT, so the client completes a secondPromiseand closes the WebSocket.
def stompClient(
received: Promise[Nothing, StompFrame],
disconnected: Promise[Nothing, Unit],
): WebSocketApp[Any] =
Handler.webSocket { channel =>
channel.receiveAll {
case ChannelEvent.UserEventTriggered(ChannelEvent.UserEvent.HandshakeComplete) =>
sendStomp(channel, connectFrame)
case ChannelEvent.Read(frame: WebSocketFrame.Binary) =>
frame.asStompFrame.flatMap { stomp =>
stomp.command match {
case StompCommand.Connected =>
Console.printLine(s"connected, session ${stomp.header("session").getOrElse("none")}") *>
sendStomp(channel, subscribeFrame) *>
sendStomp(channel, sendFrame)
case StompCommand.Message =>
received.succeed(stomp) *>
sendStomp(channel, StompFrame.disconnect(receipt = Some("disconnect-1")))
case StompCommand.Receipt =>
disconnected.succeed(()) *> channel.shutdown
case _ =>
ZIO.unit
}
}
case _ =>
ZIO.unit
}
}
The client waits for CONNECTED before it subscribes, so its SUBSCRIBE and SEND frames go into a STOMP session the server has opened.
Running the Conversation
The program installs the routes on the server, connects the client, and waits for both promises. The server binds to any free port, and Server.install returns that port, so the client connects to it. connect returns as soon as the WebSocket handshake is done, and the WebSocket stays open until the Scope closes, so the waiting happens inside ZIO.scoped:
val conversation: ZIO[Server with Client, Throwable, Unit] =
for {
port <- Server.install(routes)
received <- Promise.make[Nothing, StompFrame]
disconnected <- Promise.make[Nothing, Unit]
message <- ZIO.scoped {
stompClient(received, disconnected).connect(s"ws://localhost:$port/stomp") *>
received.await <* disconnected.await
}
_ <- Console.printLine(s"received on ${message.header("destination").getOrElse("?")}")
_ <- Console.printLine(s"subscription: ${message.header("subscription").getOrElse("?")}")
_ <- Console.printLine(s"body: ${message.body.getOrElse(Chunk.empty).asString(Charsets.Utf8)}")
} yield ()
val program: Task[Unit] =
conversation.provide(Server.defaultWith(_.onAnyOpenPort), Client.default)
It prints the session id from CONNECTED, and then the destination, the subscription id, and the body of the MESSAGE:
connected, session session-1
received on /topic/greetings
subscription: sub-0
body: Hello, STOMP!
The message came back with the subscription id the client chose in its SUBSCRIBE frame. A client with several subscriptions uses that header to tell which of them a message belongs to.
Talking to a Peer That Sends Text Frames
The STOMP specification does not say whether a frame travels in a binary or a text WebSocket message, and some STOMP clients and brokers send their frames as text messages. asStompFrame fails on those, so a client that talks to such a peer decodes the text with StompFrame.decode, which takes the bytes of one frame and returns either an error message or the frame:
def stompFromText(frame: WebSocketFrame.Text): IO[String, StompFrame] =
ZIO.fromEither(StompFrame.decode(Chunk.fromArray(frame.text.getBytes(Charsets.Utf8))))
def stompToText(frame: StompFrame): WebSocketFrame =
WebSocketFrame.text(frame.encode.asString(Charsets.Utf8))
stompToText is the counterpart of toWebSocketFrame for a peer that expects text messages. In a handler, a case for ChannelEvent.Read(frame: WebSocketFrame.Text) calls stompFromText the same way the binary case calls asStompFrame.
stompFromText is StompFrame.decode lifted into a ZIO effect. Decoding a MESSAGE frame that arrived as text gives back its command and its body:
val textFrame =
WebSocketFrame.Text("MESSAGE\ndestination:/topic/greetings\nsubscription:sub-0\nmessage-id:1\n\nHi\u0000")
val decoded: Either[String, StompFrame] =
StompFrame.decode(Chunk.fromArray(textFrame.text.getBytes(Charsets.Utf8)))
decoded.map(_.command)
// res3: Either[String, StompCommand] = Right(value = Message)
decoded.map(_.body.map(_.asString(Charsets.Utf8)))
// res4: Either[String, Option[String]] = Right(value = Some(value = "Hi"))
Putting It Together
The complete example is the endpoint of Serving a STOMP Endpoint, the client of Writing the STOMP Client, and the program of Running the Conversation in one ZIOAppDefault, with the frames of Building STOMP Frames and the sendStomp helper. The value program of that section is the app's run, so the example runs the conversation once and exits:
//> using scala 2.13.18
//> using dep "dev.zio::zio-http-stomp:3.12.0"
// Run from this folder: scala-cli run CompleteExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.stomp.CompleteExample"
package example.stomp
import zio._
import zio.http._
import zio.http.stomp._
/**
* Talk STOMP over WebSocket — Putting It Together
*
* Serves a small STOMP endpoint on a free port, connects a STOMP client to it,
* subscribes to `/topic/greetings`, sends one message there, receives it back,
* disconnects, and exits.
*/
object CompleteExample extends ZIOAppDefault {
val connectFrame: StompFrame =
StompFrame.connect(host = "localhost")
val subscribeFrame: StompFrame =
StompFrame.subscribe(destination = "/topic/greetings", id = "sub-0")
val sendFrame: StompFrame =
StompFrame.send("/topic/greetings", "Hello, STOMP!", Some("text/plain"), Map.empty[String, String])
def sendStomp(channel: WebSocketChannel, frame: StompFrame): Task[Unit] =
channel.send(ChannelEvent.Read(frame.toWebSocketFrame))
val stompServer: WebSocketApp[Any] =
Handler.webSocket { channel =>
Ref.make(Map.empty[String, String]).flatMap { subscriptions =>
channel.receiveAll {
case ChannelEvent.Read(frame: WebSocketFrame.Binary) =>
frame.asStompFrame.flatMap { stomp =>
stomp.command match {
case StompCommand.Connect =>
sendStomp(channel, StompFrame.connected(session = Some("session-1")))
case StompCommand.Subscribe =>
val destination = stomp.header("destination").getOrElse("")
val id = stomp.header("id").getOrElse("")
subscriptions.update(_ + (destination -> id))
case StompCommand.Send =>
val destination = stomp.header("destination").getOrElse("")
subscriptions.get.flatMap { subs =>
ZIO.foreachDiscard(subs.get(destination)) { subscriptionId =>
Random.nextUUID.flatMap { messageId =>
sendStomp(
channel,
StompFrame.message(
destination = destination,
messageId = messageId.toString,
subscription = subscriptionId,
body = stomp.body.getOrElse(Chunk.empty),
contentType = stomp.header("content-type"),
),
)
}
}
}
case StompCommand.Disconnect =>
ZIO.foreachDiscard(stomp.header("receipt")) { receiptId =>
sendStomp(channel, StompFrame.receipt(receiptId))
}
case _ =>
ZIO.unit
}
}
case _ =>
ZIO.unit
}
}
}
val routes: Routes[Any, Response] =
Routes(Method.GET / "stomp" -> handler(stompServer.toResponse))
def stompClient(
received: Promise[Nothing, StompFrame],
disconnected: Promise[Nothing, Unit],
): WebSocketApp[Any] =
Handler.webSocket { channel =>
channel.receiveAll {
case ChannelEvent.UserEventTriggered(ChannelEvent.UserEvent.HandshakeComplete) =>
sendStomp(channel, connectFrame)
case ChannelEvent.Read(frame: WebSocketFrame.Binary) =>
frame.asStompFrame.flatMap { stomp =>
stomp.command match {
case StompCommand.Connected =>
Console.printLine(s"connected, session ${stomp.header("session").getOrElse("none")}") *>
sendStomp(channel, subscribeFrame) *>
sendStomp(channel, sendFrame)
case StompCommand.Message =>
received.succeed(stomp) *>
sendStomp(channel, StompFrame.disconnect(receipt = Some("disconnect-1")))
case StompCommand.Receipt =>
disconnected.succeed(()) *> channel.shutdown
case _ =>
ZIO.unit
}
}
case _ =>
ZIO.unit
}
}
val conversation: ZIO[Server with Client, Throwable, Unit] =
for {
port <- Server.install(routes)
received <- Promise.make[Nothing, StompFrame]
disconnected <- Promise.make[Nothing, Unit]
message <- ZIO.scoped {
stompClient(received, disconnected).connect(s"ws://localhost:$port/stomp") *>
received.await <* disconnected.await
}
_ <- Console.printLine(s"received on ${message.header("destination").getOrElse("?")}")
_ <- Console.printLine(s"subscription: ${message.header("subscription").getOrElse("?")}")
_ <- Console.printLine(s"body: ${message.body.getOrElse(Chunk.empty).asString(Charsets.Utf8)}")
} yield ()
val run =
conversation.provide(Server.defaultWith(_.onAnyOpenPort), Client.default)
}
It prints the same lines as the program in Running the Conversation:
connected, session session-1
received on /topic/greetings
subscription: sub-0
body: Hello, STOMP!
Running the Examples
All runnable code from this guide is in zio-http-example/src/main/scala/example/stomp/. Run any file from that folder with scala-cli run <File>.scala, or from the repository root with sbt "zioHttpExample/runMain example.stomp.<ObjectName>".
Going Further
- A STOMP broker can require the client to ask for a STOMP subprotocol, such as
v12.stomp, in the WebSocket handshake.stompClient(received, disconnected).withConfig(WebSocketConfig.default.subProtocol(Some("v12.stomp")))makes the client send it. StompFramehas constructors for the other STOMP commands:unsubscribe,ackandnackfor client acknowledgement,begin,commitandabortfor transactions, anderrorfor a server that rejects a frame.StompVersion.parseAcceptVersionsandStompVersion.negotiatepick the protocol version a server answers with from theaccept-versionheader of aCONNECTframe.- Socket and WebSocketFrame cover the WebSocket API the STOMP frames travel on.
- How to Push Live Updates to the Browser serves a WebSocket to a browser and compares it with server-sent events.