elixir-socket icon indicating copy to clipboard operation
elixir-socket copied to clipboard

Starting an UDP socket as a process?

Open seivan opened this issue 6 years ago • 2 comments

Do I store the socket as part of a GenServer state, or do I start it as a child of a supervisor and let the GenServer reference it by a name and vice versa, socket to GenServer?

~Is there a way to listen (like handle_info) for new messages instead of blocking with receive/1?~

seivan avatar Apr 16 '18 10:04 seivan

I think I figured a few things out, but I am not sure if it's correct.

defmodule Network do

end
defmodule Network.Server do
  use GenServer

  @port 1337
  @address {127, 0, 0, 1}


  def start_link(arg) do
    GenServer.start_link(__MODULE__, arg, name: __MODULE__)
  end

  def init(_args) do
    Process.send_after self(), :socket, 0
    {:ok, []}
  end

  def handle_info(:socket, _state) do
    server = Socket.UDP.open!(@port, mode: :active)
    Socket.UDP.process!(server, self())
    {:noreply, []}
  end

  def handle_info({:udp, _server, _address, _port, data}, state) do
    {:noreply, state ++ [data]}
  end

  def handle_call(:get, _from, state) do
    {:reply, state, state}
  end

  defp p, do: @port
  defp a, do: @address
  def server, do: {a(), p()}

end
  1. Is Socket.UDP.process/2 necessary?
  2. How do I close a UDP socket once I'm done?
  3. Can I reuse a Socket or should I close it?

seivan avatar Apr 16 '18 11:04 seivan

  1. Socket.UDP.process is necessary if the process you want the messages to be sent is different from the one that opened it.
  2. Socket.close(socket)
  3. Probably, depends on what you're doing, UDP sockets don't create connections so it should be fine.

meh avatar Jul 15 '18 21:07 meh