Skip to content

Instantly share code, notes, and snippets.

@oscherler
Created May 3, 2017 20:14
Show Gist options
  • Save oscherler/0a37b8305a2a811ede7578818a6b0063 to your computer and use it in GitHub Desktop.
Save oscherler/0a37b8305a2a811ede7578818a6b0063 to your computer and use it in GitHub Desktop.
Palindrome checking server in Erlang.
-module( server ).
-export( [ server/1, server/0, client/2, balancer/2, balancer/1, demo/2 ] ).
% server/1, reply to the spawning process
server( Pid ) ->
receive
{ check, Text } ->
reply( Pid, reply_message( Text ) ),
server( Pid );
_ -> ok
end.
% server/0, receive from multiple clients
server() ->
receive
{ check, Text, Pid } ->
reply( Pid, reply_message( Text ) ),
server();
_ -> ok
end.
% client to test server/0
client( Text, Server ) ->
Server ! { check, Text, self() },
receive
{ result, Result } -> io:format( "~s~n", [ Result ] );
_ -> nok
end.
% simple load balancer between two servers
balancer( S1, S2 ) ->
receive
Msg = { check, _Text, _Pid } ->
S1 ! Msg,
balancer( S2, S1 );
_ ->
ok
end.
% round robin load balancer with a list of servers
balancer( [ S | Ss ] ) ->
receive
Msg = { check, _Text, _Pid } ->
S ! Msg,
balancer( Ss ++ [ S ] );
_ ->
ok
end.
% demo: spawns NServers servers, a round robin load balancer,
% and sends it NMessages messages.
demo( NServers, NMessages ) ->
Servers = lists:map(
fun( _I ) -> spawn( server, server, [] ) end,
lists:seq( 1, NServers )
),
Balancer = spawn( server, balancer, [ Servers ] ),
lists:map(
fun( I ) -> server:client( demo_text( I ), Balancer ) end,
lists:seq( 1, NMessages )
).
demo_text( I ) when I rem 2 == 0 ->
"foo";
demo_text( _I ) ->
"foof".
reply_message( Text ) ->
lists:flatten( reply_message( palin:palindrome( Text ), Text ) ).
reply_message( true, Text ) ->
io_lib:format( "[~p] \"~s\" is a palindrome.", [ self(), Text ] );
reply_message( _, Text ) ->
io_lib:format( "[~p] \"~s\" is not a palindrome.", [ self(), Text ] ).
reply( Pid, Msg ) ->
Pid ! { result, Msg }.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment