SHARE
TWEET

Untitled

a guest Jun 16th, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -module(ping_pong).
  2.  
  3. -export([
  4.     start_pong/0,
  5.     ping/1,
  6.     ping/2,
  7.     pong/1,
  8.     bad_ping/1,
  9.     terminate/1,
  10.     test_ping/0]).
  11.  
  12. %%
  13. % multiple ping with termination in the end.
  14. %
  15. ping(0, Pong_PID) ->
  16.     terminate(Pong_PID),
  17.     io:format("ping finished~n", []);
  18.  
  19. ping(N, Pong_PID) ->
  20.     ping(Pong_PID),
  21.     ping(N - 1, Pong_PID).
  22.  
  23. %%
  24. % single ping with no termination.
  25. %
  26. ping(Pong_PID) ->
  27.     MyPid = self(),
  28.     Pong_PID ! {ping, MyPid},
  29.     receive
  30.         pong ->
  31.             io:format("Ping ~p received pong~n", [MyPid])
  32.     end.
  33.  
  34. bad_ping(Pong_PID) ->
  35.     MyPid = self(),
  36.     Pong_PID ! {bad, MyPid},
  37.     io:format("Bad Ping pid is ~p~n", [MyPid]),
  38.     receive
  39.         pong ->
  40.             io:format("Bad Ping should never received pong~n", [])
  41.     after 5000 ->
  42.         io:format("Ping timed out ~n", [])
  43.     end.
  44. %%
  45. % Termination of pong.
  46. %
  47. terminate(Pong_PID) ->
  48.     Pong_PID ! finished.
  49.  
  50. %%
  51. % pong.
  52. %
  53. pong(N) ->
  54.     io:format("Pong pid ~p~n", [self()]),
  55.     {Pinged, Incorrect} = N,
  56.     receive
  57.         finished ->
  58.             io:format("Pong finished total received valid ping ~p, invalid message ~p~n", [Pinged, Incorrect]);
  59.         {ping, Ping_PID} ->
  60.             io:format("Pong received ping~p~n", [Ping_PID]),
  61.             Ping_PID ! pong,
  62.             pong({Pinged+1, Incorrect});
  63.         _ ->
  64.             io:format("wrong message~n"),
  65.             pong({Pinged, Incorrect+1})
  66.     end.
  67.  
  68. start_pong() ->
  69.     pong({0,0}).
  70.  
  71. %%
  72. % local test
  73. %
  74. test_ping() ->
  75.     Pong_PID = spawn(ping_pong, pong, [{0,0}]),
  76.     spawn(ping_pong, ping, [3, Pong_PID]).
  77.  
  78. %%
  79. % Two nodes ping_pong.
  80. % 1. nodes are started with erl -sname <short node name> or rebar3 shell --sname <short node name>
  81. % 2. node(). % the remote node
  82. % 3. start ping_pong:start_pong().
  83. % 4. set RemoteNode on the other node
  84. % 5. rpc:call(RemoteNode, erlang, whereis, [user]). % get the remote part of pid
  85. % 6. rpc:call(RemoteNode, ping_pong, ping, [5, <pid>]). % on the other node
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top