1
votes

So my goal is to start a client process first. Then be able to register it to a specified server. Done in two steps.

I initially create my client/server processes like so:

startServer() -> register(chat, spawn(chat, loop, [[], []])).
startClient() -> register(clientPid, spawn(chat, client, [undefined, undefined])).

Which goes runs the client loop:

client(Server, Username) ->
receive
    {online, Server, Username} ->
        {chat, Server} ! {self(), online, Username},
        reply();
end,
client(Server, Username).

This then goes back my server process:

loop(Userlist, Chatlist) ->
receive
{From, online, Username} ->
        List = tryGoOnline(From, Username, Userlist),
        loop(List, Chatlist);
end.

Then the user tries to go online depending if the same name is registered or not in the list.

tryGoOnline(From, Username, Userlist) ->
case lists:keymember(Username, 2, Userlist) of
    true ->
        From ! {chat, existing, close, "This username is in use. Please choose a different name."},
        Userlist;
    false ->
        From ! {chat, "You successfully logged online!"},
        [{From, Username} | Userlist]
end.

This is all called from my goOnline function:

goOnline(Username, Server) ->
case whereis(clientPid) of 
    undefined -> "You must register the client first!";
    _ -> clientPid ! {online, Server, Username}   **///PROBLEM HERE!!**
end.

I did a debug of io:fwrite("~p~n",[clientPid]) in the goOnline function and it kept coming back with the word 'clientPid'... not the PID id. This is causing the client process not to receive the message and the code stops there. There must be something wrong with my startClient() call. I'm not sure what to pass into the client process since the server and username are unknown at the creation. Any help would be awesome. I hope all this makes sense.

My reply() function too:

 reply() ->
 receive
    {chat, existing, close, Error} ->
        io:format("~p~n", [Error]),
        exit(existing);
    {chat, close, Error} -> 
        io:format("~p~n", [Error]);
    {chat, NoError} -> 
        io:format("~p~n", [NoError])
end.
1

1 Answers

0
votes

This line:

_ -> clientPid ! {online, Server, Username}

Should be:

ClientPID -> ClientPID ! {online, Server, Username}

whereis gives you the PID registered with the atom.

What you were doing is sending message to the atom clientPid, not to the PID registered with this atom.