-module(udp_test).
-export([start_server/0,client/1]).
start_server()->
spawn(fun()->server(4000) end).
server(Port)->
{ok,Socket}=gen_udp:open(Port,[binary]),
io:format(“server opened socket:pn”,[Socket]),
loop(Socket).
loop(Socket)->
receive
{udp,Socket,Host,Port,Bin}=Msg->
io:format(“server received:pn”,[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).
client(N)->
{ok,Socket}=gen_udp:open(0,[binary]),
io:format(“client opened socket=pn”,[Socket]),
ok=gen_udp:send(Socket,“localhost”,8000,term_to_binary(N)),
Value=receive
{udp,Socket,,,Bin}=Msg->
io:format(“client recieved:pn”,[Msg]),
binary_to_term(Bin)
after 4000->
17
end,
gen_udp:close(Socket),
Value.
Erlang程序设计(第2版)【瑞典】Joe Armstrong 著 牛化成译 【M】北京:中国工信出版社和人民邮电出版社