-
-
Save chgeuer/18989b143142dbe91d2153046cf3c340 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env elixir | |
Mix.install( | |
[ | |
{:websockex, "~> 0.4.3"} | |
], | |
start_applications: true | |
) | |
defmodule WebSocketExample do | |
use WebSockex | |
def start_link(url) do | |
state = nil | |
WebSockex.start_link(url, __MODULE__, state) | |
end | |
def handle_connect(_conn, state) do | |
IO.puts("Connected (handle_connect/2 called)") | |
schedule_alert() | |
{:ok, state} | |
end | |
defp schedule_alert() do | |
Process.send_after(self(), :foo_bar, :timer.seconds(4)) | |
end | |
def handle_info(:foo_bar, state) do | |
schedule_alert() | |
type = :text | |
message = "request_timer" | |
frame = {type, message} | |
{:reply, frame, state} | |
end | |
def handle_cast({:send, {type, msg} = frame}, state) do | |
IO.puts "Sending #{type} frame with payload: #{msg}" | |
{:reply, frame, state} | |
end | |
def handle_frame({:text, msg}, state) do | |
IO.puts "handle_frame({:text, \"#{msg}\"}, #{inspect(state)})" | |
{:ok, state} | |
end | |
def start(url) do | |
case __MODULE__.start_link(url) do | |
{:error, reason} -> | |
IO.puts("Not yet ready.... #{inspect reason}") | |
Process.sleep(500) | |
start(url) | |
{:ok, pid} -> {:ok, pid} | |
end | |
end | |
end | |
url = "https://kobrakai.de/ws/connection_timer/blogpost" | |
{:ok, _pid} = WebSocketExample.start(url) | |
Process.sleep(:infinity) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment