Hi,
I’m learning elixir and the current use case I’m now playing with is a websocket server with plug_cowboy
and a client with websockex
. Server is working nice if I test with websocat
or other clients.
My main issue is that while coding a simple test case where the client sends a message and the test finishes (ends the process, as I understand, which may be wrong) before actually receiving the response. I suspect I’m missing some kind of loop that keeps reading the socket for incoming messages instead of just sending a message and finishing the process [because no more code is left to be run].
My code is as follows, test client first:
use WebSockex
require Logger
def start(url, state) do
WebSockex.start(url, __MODULE__, state)
end
def request(client, message) do
Logger.info("Sending request: #{inspect message}")
WebSockex.send_frame(client, {:text, message})
end
def handle_connect(_conn, state) do
Logger.info("Connected")
{:ok, state}
end
def handle_frame({:text, msg}, state) do
Logger.info "Received a message: #{inspect msg}"
{:ok, state}
end
def handle_cast({:send, {type, msg} = frame}, state) do
IO.puts "Sending #{type} frame with payload #{inspect msg}"
{:reply, frame, state}
end
def terminate(_reason, _state) do
IO.puts("terminate")
exit(:normal)
end
end
And the test:
{:ok, pid} = Client.start("ws://localhost:4444/", %{})
Client.request(pid, Jason.encode!(%{msg: "hi there"}))
# something missing here to keep Client connected and later call Client.stop
end
Thanks in advance!