Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(ping_pong).
- -export([
- start_pong/0,
- ping/1,
- ping/2,
- pong/1,
- bad_ping/1,
- terminate/1,
- test_ping/0]).
- %%
- % multiple ping with termination in the end.
- %
- ping(0, Pong_PID) ->
- terminate(Pong_PID),
- io:format("ping finished~n", []);
- ping(N, Pong_PID) ->
- ping(Pong_PID),
- ping(N - 1, Pong_PID).
- %%
- % single ping with no termination.
- %
- ping(Pong_PID) ->
- MyPid = self(),
- Pong_PID ! {ping, MyPid},
- receive
- pong ->
- io:format("Ping ~p received pong~n", [MyPid])
- end.
- bad_ping(Pong_PID) ->
- MyPid = self(),
- Pong_PID ! {bad, MyPid},
- io:format("Bad Ping pid is ~p~n", [MyPid]),
- receive
- pong ->
- io:format("Bad Ping should never received pong~n", [])
- after 5000 ->
- io:format("Ping timed out ~n", [])
- end.
- %%
- % Termination of pong.
- %
- terminate(Pong_PID) ->
- Pong_PID ! finished.
- %%
- % pong.
- %
- pong(N) ->
- io:format("Pong pid ~p~n", [self()]),
- {Pinged, Incorrect} = N,
- receive
- finished ->
- io:format("Pong finished total received valid ping ~p, invalid message ~p~n", [Pinged, Incorrect]);
- {ping, Ping_PID} ->
- io:format("Pong received ping~p~n", [Ping_PID]),
- Ping_PID ! pong,
- pong({Pinged+1, Incorrect});
- _ ->
- io:format("wrong message~n"),
- pong({Pinged, Incorrect+1})
- end.
- start_pong() ->
- pong({0,0}).
- %%
- % local test
- %
- test_ping() ->
- Pong_PID = spawn(ping_pong, pong, [{0,0}]),
- spawn(ping_pong, ping, [3, Pong_PID]).
- %%
- % Two nodes ping_pong.
- % 1. nodes are started with erl -sname <short node name> or rebar3 shell --sname <short node name>
- % 2. node(). % the remote node
- % 3. start ping_pong:start_pong().
- % 4. set RemoteNode on the other node
- % 5. rpc:call(RemoteNode, erlang, whereis, [user]). % get the remote part of pid
- % 6. rpc:call(RemoteNode, ping_pong, ping, [5, <pid>]). % on the other node
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement