In the previous part of this series, we discovered how to create persistent connections in Rack in theory, but now we'll put what we learned into

Server-sent Events and WebSockets in Rack for Ruby

submited by
Style Pass
2024-11-27 12:00:07

In the previous part of this series, we discovered how to create persistent connections in Rack in theory, but now we'll put what we learned into practice.

The web has two formalized specifications for communication over a persistent connection: server-sent events (SSEs) and WebSockets.

Server-sent events (SSEs) enable a client to hold an open connection with the server, but only the server can publish messages to the client. It isn't a bi-directional protocol.

The API is encapsulated in the EventSource class and new messages from the server trigger events that we listen for. Next, we need to build the endpoint that sends the events:

From a server point of view, this is fairly similar to the streaming bodies example we used in the previous part of this series. It's worth noting the content-type header and the string format written back to the client.

Open up localhost:9292 on your web browser, and you'll see the time written to the document five times at one-second intervals.

Leave a Comment