Julep

WebSocket clients for Elixir, built on Mint and Mint.WebSocket.

A Julep client is a GenServer that speaks WebSocket. It handles the nuances of the protocol for you, from the upgrade to the closing handshake, and comes with what a long-lived connection needs:

Julep is at a release candidate, and its API may change before 0.1.0.

Installation

Requires Elixir 1.17 or later. Tested on OTP 27 to 29.

def deps do
  [
    {:julep, "~> 0.1.0-rc.1"}
  ]
end

Usage

defmodule MyApp.Ticker do
  use Julep

  def start_link(url), do: Julep.start_link(__MODULE__, url: url)

  @impl Julep
  def init(_arg), do: {:ok, %{}}

  @impl Julep
  def handle_connect(state),
    do: {:noreply, state, {:send, {:text, ~s({"subscribe":"ticker"})}}}

  @impl Julep
  def handle_frame({:text, json}, state) do
    IO.puts(json)
    {:noreply, state}
  end

  @impl Julep
  def handle_disconnect(_reason, state), do: {:reconnect, state}

  @impl Julep
  def prepare(:upgrade, request, _state) do
    timestamp = Integer.to_string(System.os_time(:second))
    %{request | headers: [{"x-timestamp", timestamp} | request.headers]}
  end

  def prepare(_stage, request, _state), do: request
end

Start it under a supervisor:

children = [{MyApp.Ticker, "wss://example.com/ws"}]

Or start it and wait for the first connection:

{:ok, pid} = Julep.connect(MyApp.Ticker, url: "wss://example.com/ws")

Limits

Documentation

The documentation is on HexDocs:

License

Julep is released under the MIT License. See LICENSE.