Skip to content

Instantly share code, notes, and snippets.

@LostKobrakai
Forked from chgeuer/websocket_testclient.exs
Created May 31, 2024 12:54
Show Gist options
  • Save LostKobrakai/364b93e346a224218145121857f268c5 to your computer and use it in GitHub Desktop.
Save LostKobrakai/364b93e346a224218145121857f268c5 to your computer and use it in GitHub Desktop.
#!/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