Created
May 9, 2017 19:01
-
-
Save Azolo/75f6a304b9a835d54c25a8ab543630a0 to your computer and use it in GitHub Desktop.
WebSockex Wrapped Indefinite Reconnect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Container do | |
use GenServer | |
def start_link(url, state \\ %{}) when is_map(state) do | |
GenServer.start_link(__MODULE__, Map.put(state, :connection_url, url), []) | |
end | |
def cast_frame(pid, frame) do | |
GenServer.cast(pid, {:frame, frame}) | |
end | |
def init(state) do | |
{:ok, socket_pid} = connect_websocket(state.url) | |
{:ok, Map.put(state, :socket_pid, socket_pid)} | |
end | |
def handle_cast({:frame, frame}, state) do | |
# Do Fun Stuff Here | |
end | |
def handle_info({:DOWN, _, :process, pid, _}, %{socket_pid: socket_pid} = state) | |
when pid == socket_pid do | |
{:ok, new_socket_pid} = connect_websocket(state.url) | |
{:ok, %{state | socket_pid: new_socket_pid} | |
end | |
defp connect_websocket(url) do | |
case WebSocket.start_link(url) do | |
{:ok, pid} -> | |
Process.unlink(pid) | |
Process.monitor(pid) | |
{:ok, pid} | |
{:error, %WebSockex.ConnError{}} -> | |
# Backoff here if you want | |
connect_websocket(url) | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule WebSocket do | |
use WebSockex.Client | |
def start_link(url, parent) do | |
WebSockex.Client.start_link(url, __MODULE__, parent) | |
end | |
def handle_frame(frame, parent) do | |
Container.cast_frame(parent, frame) | |
{:ok, parent} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment