Created
March 19, 2012 19:54
-
-
Save dgabriele/2125936 to your computer and use it in GitHub Desktop.
Simple Client/Server Model in Erlang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(server). | |
-export([factorial/2, factorial/1, client/2, server/1, start/0]). | |
%% BACKLOG is effectively the number of clients | |
-define(BACKLOG, 1000). | |
factorial(1) -> | |
1; | |
factorial(X) -> | |
X * factorial(X-1). | |
factorial(Client, X) -> | |
Client ! factorial(X). | |
client(Data, ServerPID) -> | |
ServerPID ! {fact, self(), Data}, | |
receive | |
Reply -> io:format("Client ~w got fact(~p)=~p.~n", | |
[self(), Data, Reply]) | |
end. | |
server(0) -> | |
ok; | |
server(Backlog) -> | |
receive | |
{fact, Client, Data} -> | |
spawn(?MODULE, factorial, [Client, Data]) | |
end, | |
server(Backlog-1). | |
start(0, _ServerPID) -> | |
ok; | |
start(N, ServerPID) -> | |
spawn(?MODULE, client, [random:uniform(10), ServerPID]), | |
start(N-1, ServerPID). | |
start() -> | |
start(?BACKLOG, spawn(?MODULE, server, [?BACKLOG])). | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment