Getting started with WebSockex

WebSockex is my go-to library for writing web socket clients in Elixir. Here's an absolute bare bones guide to getting started.

Create a mix project

mix new sockets

Install the dependency

Add web_sockex to the deps in your mix.exs file.

  # Run "mix help deps" to learn about dependencies.
  defp deps do
    [
      {:websockex, "~> 0.4.3"}
    ]
  end

Then fetch it

mix deps.get

Writing a client

Now, you'll be able to bring in functionality to make a module act as a web socket client by adding use WebSockex to the top of it.

You'll need to define a start or a start_link function to make the connection to the remote web socket server and at a minimum, you'll also need to handle incoming frames with handle_frame/2.

If you've worked with GenServers, the syntax should be familiar. In the function heads, pattern match on the incoming message and the state. Then return a tuple with a response and state. E.g. {:ok, state} or {:reply, response, state}.

Return {:close, state} to disconnect.

The full module

defmodule EchoClient do
  use WebSockex
  require Logger

  @echo_server "wss://echo.websocket.org/?encoding=text"
  def start_link(opts \\ []) do
    socket_opts = [
      ssl_options: [
        ciphers: :ssl.cipher_suites(:all, :"tlsv1.3")
      ]
    ]
    opts = Keyword.merge(opts, socket_opts)
    WebSockex.start_link(@echo_server, __MODULE__, %{}, opts)
  end

  def handle_frame({:text, "please reply" = msg}, state) do
    Logger.info("Echo server says, #{msg}")
    reply = "Back, atcha!"

    Logger.info("Sent to Echo server: #{reply}")
    {:reply, {:text, reply}, state}
  end

  def handle_frame({:text, "shut down"}, state) do
    Logger.info("shutting down...")
    {:close, state}
  end

  def handle_frame({:text, msg}, state) do
    Logger.info("Echo server says, #{msg}")
    {:ok, state}
  end

  def handle_disconnect(%{reason: reason}, state) do
    Logger.info("Disconnect with reason: #{inspect reason}")
    {:ok, state}
  end
end
Back to index

No Comments