/jaerlang-code/code/udp_test.erl

https://github.com/killme2008/erlib · Erlang · 53 lines · 33 code · 10 blank · 10 comment · 0 complexity · 5cb30031aa6255ed80fe80f07bba4e85 MD5 · raw file

  1. %% ---
  2. %% Excerpted from "Programming Erlang",
  3. %% published by The Pragmatic Bookshelf.
  4. %% Copyrights apply to this code. It may not be used to create training material,
  5. %% courses, books, articles, and the like. Contact us if you are in doubt.
  6. %% We make no guarantees that this code is fit for any purpose.
  7. %% Visit http://www.pragmaticprogrammer.com/titles/jaerlang for more book information.
  8. %%---
  9. -module(udp_test).
  10. -export([start_server/0, client/1]).
  11. start_server() ->
  12. spawn(fun() -> server(4000) end).
  13. %% The server
  14. server(Port) ->
  15. {ok, Socket} = gen_udp:open(Port, [binary]),
  16. io:format("server opened socket:~p~n",[Socket]),
  17. loop(Socket).
  18. loop(Socket) ->
  19. receive
  20. {udp, Socket, Host, Port, Bin} = Msg ->
  21. io:format("server received:~p~n",[Msg]),
  22. N = binary_to_term(Bin),
  23. Fac = fac(N),
  24. gen_udp:send(Socket, Host, Port, term_to_binary(Fac)),
  25. loop(Socket)
  26. end.
  27. fac(0) -> 1;
  28. fac(N) -> N * fac(N-1).
  29. %% The client
  30. client(N) ->
  31. {ok, Socket} = gen_udp:open(0, [binary]),
  32. io:format("client opened socket=~p~n",[Socket]),
  33. ok = gen_udp:send(Socket, "localhost", 4000,
  34. term_to_binary(N)),
  35. Value = receive
  36. {udp, Socket, _, _, Bin} = Msg ->
  37. io:format("client received:~p~n",[Msg]),
  38. binary_to_term(Bin)
  39. after 2000 ->
  40. 0
  41. end,
  42. gen_udp:close(Socket),
  43. Value.