elixir-socket
elixir-socket copied to clipboard
Starting an UDP socket as a process?
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
?~
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
- Is
Socket.UDP.process/2
necessary? - How do I close a UDP socket once I'm done?
- Can I reuse a Socket or should I close it?
-
Socket.UDP.process
is necessary if the process you want the messages to be sent is different from the one that opened it. -
Socket.close(socket)
- Probably, depends on what you're doing, UDP sockets don't create connections so it should be fine.