Hi. I’ve got a genserver application that is working well, but a new requirement is that upon a call (or cast) request, I need to send a udp packet to another service. I can’t get this to work, and I fear that I’m missing knowledge of some part of the GenServer architecture. I’ve searched the web and this forum, but haven’t found anything that indicates it shouldn’t work.
Starting with what works:
get the socket from the genserver and send the packet:
{:ok, socket} = GenServer.call(ScEm, :get_socket)
:gen_udp.send(socket, ip, port, packet)
At this point, the server receives the message correctly.
But, in the context of the genserver itself, the following code never sends the packet:
defmodule ScEm do
use GenServer
…
@impl true
def handle_call({:send, packet}, _from, %State{socket: socket, ip: ip, port: port} = state) do
Logger.info(“sending = #{packet} to ip #{format_ip(ip)} port #{port}”)
response = :gen_udp.send(socket, ip, port, packet)
{:reply, response, state}
end
…
end
When I invoke the server with:
GenServer.call(ScEm, {:send, packet})
the external service doesn’t get anything. In the genserver’s log, I see that the ip and port are correct, and I know the socket is correct since in my working repl example, it is using the same socket.