I do not think I should explain UDP protocol itself, if you are interested you may learn it from Wiki. Today I am going to provide a couple of examples of UDP socket usage in Erlang. Basically it is very simple and I think that is main reason why there not much example cam befound in the Internet. Anyway, I think that someone can find this example helpful.
Following code is a simple example of UDP echo server:
-module(server).
-export([start/0, client/1]).
start() ->
spawn(fun() -> server(4000) end).
server(Port) ->
{ok, Socket} = gen_udp:open(Port, [binary, {active, false}]),
io:format("server opened socket:~p~n",[Socket]),
loop(Socket).
loop(Socket) ->
inet:setopts(Socket, [{active, once}]),
receive
{udp, Socket, Host, Port, Bin} ->
io:format("server received:~p~n",[Bin]),
gen_udp:send(Socket, Host, Port, Bin),
loop(Socket)
end.
% Client code
client(N) ->
{ok, Socket} = gen_udp:open(0, [binary]),
io:format("client opened socket=~p~n",[Socket]),
ok = gen_udp:send(Socket, "localhost", 4000, N),
Value = receive
{udp, Socket, _, _, Bin} ->
io:format("client received:~p~n",[Bin])
after 2000 ->
0
end,
gen_udp:close(Socket),
Value.
Security consideration
Here I should notice that it is important initially to open the socket in {active, false} mode and only when we are ready to process the data set it socket to {active, once} with inets:setopts/2. I have already described this in my previous article Erlang TCP server & TCP client sockets with gen_tcp, so I suggest to read it. Changing socket modes this way will prevent server overload by fast client.
Now we can compile the code and start server:
Eshell V5.8.5 (abort with ^G)
1> c(server).
{ok,server}
2> server:start().
<0.38.0>
server opened socket:#Port<0.2519>
server received:<<"Hello">>
On other node lets start client
Eshell V5.8.5 (abort with ^G) 1> server:client(<<"Hello">>). client opened socket=#Port<0.594> client received:<<"Hello">> ok
I have not used Erlang/OTP gen_server behaviour here, as it is quite simple to do. But let me know if you are interested in such code and I will publich it. Follow my blog for more articles.