meh / elixir-socket

Socket wrapping for Elixir.
691 stars 119 forks source link

Starting an UDP socket as a process? #93

Open seivan opened 6 years ago

seivan commented 6 years ago

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 commented 6 years ago

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?
meh commented 6 years ago
  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.