smart_websocket_client v0.1.0 SmartWebsocketClient.Listener behaviour

Behaviour to act on received messages.

Example

defmodule MyListener do
  use SmartWebsocketClient.Listener

  def on_receive(msg) do
    IO.inspect msg
  end
end

Summary

Callbacks

What to do when a ping message is received

What to do when an unknown message is received

Callback function that is called every time a message is received

Blocking infinite loop that waits for received messages and dispatches to the relevant handler when a message is received

Callbacks

handle_ping(socket)
handle_ping(socket :: any) :: any

What to do when a ping message is received.

You don’t need to override/implement this callback unless you want to extend the default behaviour.

Default implementation

def handle_ping(socket) do
  socket
  |> SmartWebsocketClient.Socket.send(:pong)
end
handle_unknown(socket)
handle_unknown(socket :: any) :: any

What to do when an unknown message is received.

This is the type of function that should never be called…

You don’t need to override/implement this callback unless you want to extend the default behaviour.

Default implementation

def handle_unknown(socket) do
  :ok
end
on_receive(msg)
on_receive(msg :: any) :: any

Callback function that is called every time a message is received.

The received message is passed as an argument. You are not expected to return anything in special.

You are required to implement this callback.

Example:

def on_receive(msg) do
  IO.inspect msg
end
wait_message(socket)
wait_message(socket :: any) :: any

Blocking infinite loop that waits for received messages and dispatches to the relevant handler when a message is received.

The default implementation dispatches ping messages to handle_ping/1, text messages to on_receive/1 and “others” to handle_unknown/1.

You don’t need to override/implement this callback unless you want to extend the default behaviour.

Default implementation

def wait_message(socket) do
  socket
  |> SmartWebsocketClient.socket.recv
  |> case do
    {:text, data} ->
      on_receive(data)
    {:ping, _} ->
      handle_ping(socket)
    _ ->
      handle_unknown(socket)
  end
  wait_message(socket)
end