I was trying to implement an emoji server and write codes for it. But when I test it in the terminal it is showing timeout error. For checking the code please check the alias function for it:
-spec alias(Pid :: pid(), Short1 :: shortcode(), Short2 :: shortcode()) -> ok | {error, Reason :: term()}.
alias(Pid, Short1, Short2) when is_pid(Pid), is_list(Short1), is_list(Short2) ->
Pid ! {alias, Short1, Short2},
receive
{ok, Short2} -> ok;
{error, Reason} -> {error, Reason}
after 1000 -> {error, timeout}
end.
emoji_loop(State = #emoji_state{}) ->
receive
{alias, Short1, Short2} ->
io:format("Received alias: Short1 = ~p, Short2 = ~p~n", [Short1, Short2]),
case dict:find(Short1, State#emoji_state.shortcodes) of
{ok, _} ->
case dict:find(Short2, State#emoji_state.aliases) of
{ok, _} -> emoji_loop(State);
error ->
NewAliases = dict:store(Short2, Short1, State#emoji_state.aliases),
emoji_loop(State#emoji_state{aliases = NewAliases})
end;
error -> emoji_loop(State)
end;
end.
I have added io:format to debug the code and it seems my new_shortcode function has the issue, but I could not able to find out the issue.
Here is the input that I entered into the terminal:
{ok, Pid} = emoji:start([{"happy", <<"😄">>}, {"sad", <<"😢">>}]).
and then received the output like this:
{ok,<0.92.0>}
Then again entered another input
emoji:new_shortcode(Pid, "dollar", <<"💵"/utf8>>).
and received a message like this:
Received new_shortcode: Short = "dollar", Emo = <<240,159,146,181>>
with timeout error {error,timeout}.
How can I run the create shortcode function perfectly?
Thank you for the clarification again but still I am struggling with the stop function. Here is my code for stop function in the loop.
{stop, Pid} ->
if
Pid =:= self() ->
exit(Pid);
true ->
emoji_loop(State)
end
In this stop function I need to stop the server when write the command emoji:stop(Pid). After that the server's commands for emoji will not work and give errors. Here is the stop main function where pass the Pid as you instructed.
-spec stop(Pid :: pid()) -> ok | {error, Reason :: term()}.
stop(Pid) when is_pid(Pid) ->
Pid ! {stop, self()},
receive
ok -> ok;
{error, Reason} -> {error, Reason}
after 5000 ->
{error, timeout}
end.