为什么我的Erlang服务器没有睡觉?

时间:2014-05-23 15:09:55

标签: erlang otp

我编写了一个Erlang OTP服务器来处理游戏中的单个子弹。当我开始这个过程时,我希望它开始一个递归函数,每个请求都有一些延迟。我的问题是这种延迟似乎没有发生。我不认为'转发'的处理信息根本要求......我做错了什么?

服务器启动后,所有REPEATER字符串都会打印在终端中,没有延迟......

这是从另一台服务器发出的启动子弹的调用:

{ok,BullPid} = gen_server:start('bullet', [self(), Type, Direction, Pos, ClientMaster], []),

这是服务器:

-module('bullet').

-export([init/1, handle_info/2, handle_cast/2, terminate/2]).

repeater(0) ->
    exit(normal);
repeater(Counter) ->
    io:fwrite("REPEATER\n"),
    erlang:send_after(100, self(), forward),
    repeater(Counter-1).

init([Client, _Type, Direction, StartPos, ClientMaster]) ->
    gen_server:cast(self(), startRepeater),
    io:fwrite("BULLET INITED!!"),
    Size = {10, 10},
    {ok, {Direction, {StartPos, Size, Client}, ClientMaster}}.

handle_cast(startRepeater, {Direction, Bullet, ClientMaster}) ->
    repeater(200),
    {noreply, {Direction, Bullet, ClientMaster}}.

handle_info(forward, {Direction, {Pos, Size, Client}, ClientMaster}) ->
    io:fwrite("forward"),
    Hit = gen_server:call(ClientMaster, {bullet, {Pos, Size, Client}, Direction}),
    case Hit of
    {NewPos, object} ->
        io:fwrite("OBJECT"),
        gen_server:cast(Client, {updateBullet, {Direction, NewPos, self()}}),
        exit(normal);
    {NewPos, ID} ->
        io:fwrite("ID"),
        gen_server:cast(Client, {updateBullet, {Direction, NewPos, self()}}),
        ID ! {hit, Client},
        Client ! {frag, ID},
        exit(normal);
    {NewPos, move} ->
        io:fwrite("MOVE"),
        gen_server:cast(Client, {updateBullet, {Direction, NewPos, self()}})
    end,
    {noreply, {Direction, NewPos, ClientMaster}}.

terminate(_Reason, {_Direction, {_StartPos, _Size, Client}, _ClientMaster}) ->
    gen_server:cast(Client, {removeBullet, self()}),
    io:fwrite("bullet ~p terminated!\n", [self()]),
    ok.

1 个答案:

答案 0 :(得分:2)

您启动"转发器的方式"是错的。它的编写方式,每个转发器消息将在100毫秒后加到您的进程邮箱(加上调用转发器本身的任何延迟)。

您只需将Counter乘以您正在使用的超时即可解决此问题。例如:

repeater(0) ->
    ok; % don't exit here; exit after you *receive* the last forward message
repeater(Counter) ->
    io:fwrite("REPEATER\n"),
    erlang:send_after(100 * Counter, self(), forward),
    repeater(Counter-1).

使用此功能,您将收到Counter转发消息,每个消息由大致 100毫秒分隔。