Azolo / websockex

An Elixir Websocket Client
MIT License
519 stars 100 forks source link

How to shutdown/close websocket? #93

Open grantwest opened 3 years ago

grantwest commented 3 years ago

I couldn't find in the documentation how to close a websocket when it is no longer of any use. Is this possible? Maybe the documentation just needs a small update?

Azolo commented 3 years ago

Yeah, there's not a specific place that tells that I guess.

The answer is most of the callbacks have the option to return a {:close, state} tuple.

https://hexdocs.pm/websockex/0.4.3/WebSockex.html#c:handle_cast/2

Azolo commented 3 years ago

This is definitely a situation where I don't know where to put that particular piece of documentation.

If you have any ideas, let me know.

vipul2774 commented 2 years ago

I tried to return {:close, new_state} from handle_info/2 & handle_cast/2 but again it starts new socket connection. What am I missing? Thanks

vipul2774 commented 2 years ago

It was solved by using restart option.

defmodule MyApp.SocketClient.Socket do
  use WebSockex, restart: :temporary

  def start_link(state) do
    WebSockex.start_link("ws://localhost:4001/socket/live", __MODULE__, state)
  end

  def handle_cast({:send, {type, msg} = frame}, state) do
    {:reply, frame, state}
  end

  def handle_info(:close_socket, {t_ref, state}) do
    :timer.cancel(t_ref)
    {:close, {nil, state}}
  end

  def terminate(_, state) do
    exit(:normal)
  end
end