Joe Williams home
In an attempt to do something other than XML parsing (here and here) in Erlang this week I started playing around with Erlang processes and message passing. It's pretty cool and fairly intuitive. I wrote two small programs one a receiver and the other a sender. The receive runs as a registered PID and will recieve a message and depending on what it gets will perform an operation. The sender is a basic API that sends messages to a registered PID on a host you specify. Pretty basic but a good practice. Here's my code: message_receiver.erl
-module(message_receiver). -export([run/0, start/0]). start() -> P = spawn(message_receiver, run, []), register(msgpr, P). run() -> receive {mesg, Content} -> io:format("Message Received ~p~n", [Content]), run(); {add, Value1, Value2} -> Total = Value1 + Value2, io:format("Total: ~p~n", [Total]), run(); {file, Data} -> io:format("Output: ~p~n", [Data]), run(); stop -> io:format("Stopped ~n"); Error -> Error end.
So when message_passer:start(). is run this code will spawn and register a PID and wait for connections. Within the receive block it will perform the different operations, such as print the message, add two values and print the result or etc. message_sender.erl
-module(message_sender). -export([message/2, add/3, stop/1, file/2]). message(Host, Content) -> {msgpr, Host} ! {mesg, Content}. add(Host, Value1, Value2) -> {msgpr, Host} ! {add, Value1, Value2}. file(Host, Filename) -> {ok, Data} = file:read_file(Filename), file:close(Filename), {msgpr, Host} ! {file, Data}. stop(Host) -> {msgpr, Host} ! stop.
The sender code will send messages to the PID, for instance running message_sender:file(HOSTNAME, FILENAME). will read in the specified file and send the message containing what is in the file. message_sender:file(HOSTNAME, NUMBER, NUMBER1) will send both numbers to the receiver and the receiver will add them together. Pretty fun stuff, it's obvious how Erlang could be used as a powerful tool in distributed computing. More to come at the next (and possibly final) ErloungeSTL.
Fork me on GitHub