chat code using erlang

Upload: eyaknara

Post on 14-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 Chat code using erlang

    1/3

    -module(chat).-compile(export_all).

    startChat(Pong_Node) ->% Assigns to Ping_PID to process ID of ping% sends message to pong, passing Ping_PIDPing_PID = spawn(chat, ping, [Pong_Node]),{pong, Pong_Node} ! {ping, Ping_PID}.

    ping(Pong_Node) ->% waits for messagereceive

    {pong,Name1} ->

    Name2=("someone: "),

    % goes to pong's chatstart{pong, Pong_Node} ! chatstart,

    % sends message to pong passing Name1,Name2, and PID ofping

    {pong, Pong_Node} ! {Name1,Name2,self()},

    % goes back to pingping(Pong_Node);

    {Name1,Name2,Msg1} ->% prints the followingio:format("You: "),io:format("~s", [Msg1]),

    Bye="bye\n",Val=Msg1=:=Bye,

    % compare the message from the user with bye

    case Val oftrue ->% if equal, sends message to pong passing bye, a

    nd terminates chat after 5 seconds{pong, Pong_Node} ! bye,timer:sleep(3000),io:format("~n Your partner disconnected. ~n Ok~n

    ", []);false ->

    % if not equal, gets another message from userMsg2 = io:get_line(Name2),

    % sends message to pong passing Name1,Name2, new

    message and PID of ping{pong, Pong_Node} ! {Name1,Name2,Msg2,self()},

    % goes back to pingping(Pong_Node)

    end;

    bye ->% sends message to pong passing bye, and terminates ping

  • 7/27/2019 Chat code using erlang

    2/3

    after 5 seconds{pong, Pong_Node} ! bye,timer:sleep(3000),io:format("~nOk~n", [])

    end.

    pong()->% waits for messagereceive

    {ping, Ping_PID} ->% sends message to ping, passing pongPing_PID ! pong,

    % gets name, remove new line and add ">>"Name1=("You: "),

    % sends message to ping, passing pong and Name1Ping_PID ! {pong,Name1},pong();

    chatstart ->pong();

    {Name1, Name2, Ping_PID} ->% gets the chat message from userMsg1 = io:get_line(Name1),% sends message to ping passing Name1,Name2,and message

    from userPing_PID ! {Name1,Name2,Msg1},% goes back to pongpong();

    {Name1, Name2, Msg2, Ping_PID} ->

    % prints the followingio:format("someone: "),io:format("~s", [Msg2]),

    Bye2="bye\n",Val=Msg2=:=Bye2,

    % compare the message from the user with byecase Val oftrue ->

    % if equal, sends message to ping passing byePing_PID ! bye,

    % goes back to pongpong();

    false ->% if not equal, get another message from userMsg1 = io:get_line(Name1),

    % sends message to ping passing Name1,Name2 andnew message

    Ping_PID ! {Name1,Name2,Msg1},

  • 7/27/2019 Chat code using erlang

    3/3

    % goes back to pongpong()

    end;

    bye->% waits for 3 seconds, and prints the following.timer:sleep(3000),io:format("~nok~n", [])% pong finished

    end.

    init_chat() ->register(pong, spawn(chat, pong, [])).

    init_chat2(Pong_Node) ->spawn(chat, startChat, [Pong_Node]).