Skip to content

Instantly share code, notes, and snippets.

@xiaohanyu
Created August 13, 2017 11:48
Show Gist options
  • Save xiaohanyu/73811c5143affdac1cda957bcafdf05c to your computer and use it in GitHub Desktop.
Save xiaohanyu/73811c5143affdac1cda957bcafdf05c to your computer and use it in GitHub Desktop.
UDP server and client for factorial function.
%% udp test client and server, from joe armstrong's "programming erlang, second
%% edition"
-module(udp_test).
-export([start_server/0, client/1]).
start_server() ->
spawn(fun() -> server(4000) end).
%% the server
server(port) ->
{ok, socket} = gen_udp:open(port, [binary]),
io:format("server opened socket: ~p~n", [socket]),
loop(socket).
loop(socket) ->
receive
{udp, socket, host, port, bin} = msg ->
io:format("server received: ~p~n", [msg]),
n = binary_to_term(bin),
fac = fac(n),
gen_udp:send(socket, host, port, term_to_binary(fac)),
loop(socket)
end.
fac(0) ->
1;
fac(n) ->
n * fac(n - 1).
%% the client
client(n) ->
{ok, socket} = gen_udp:open(0, [binary]),
io:format("client opened socket = ~p~n", [socket]),
ok = gen_udp:send(socket, "localhost", 4000,
term_to_binary(n)),
value = receive
{udp, socket, _, _, bin} = msg ->
io:format("client received: ~p~n", [msg]),
binary_to_term(bin)
after 2000 ->
0
end,
gen_udp:close(socket),
value.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment