【问题标题】:How do I handle only the newest message in the erlang queue?如何只处理 erlang 队列中的最新消息?
【发布时间】:2014-06-22 23:01:51
【问题描述】:

我正在用 Erlang 编写一个游戏引擎,服务器不断向客户端发送新的位置。我只想使用最新的消息并将其余的扔掉,有什么办法可以做到吗?我在客户端使用 Jinterface,所以一个解决方案会很好。

【问题讨论】:

    标签: java erlang jinterface


    【解决方案1】:

    在 erlang 中,不可能(直接)按照你说的去做。但是您可以使用中间服务器来实现此行为。该服务器的作用是接收所有消息并保留最新消息的副本,并通过发送此消息来响应客户端请求。

    -module(latest).
    
    -compile([export_all]).
    
    
    start() ->
        P = spawn(fun() -> loop(empty) end),
        register(?MODULE,P).
    
    loop(Last) ->
        receive
            {newpos,X} -> loop(X);
            {getpos,Pid} -> Pid ! Last, loop(empty);
            stop -> stopped
        end.
    % interfaces
    
    storepos(X) -> ?MODULE ! {newpos,X}.
    
    getpos() -> 
        ?MODULE ! {getpos,self()},
        receive
            M -> M
        end.
    
    stop() -> ?MODULE ! stop.
    
    % test func
    
    test() ->
        start(),
        P1 = spawn(fun() -> posloop(0) end),
        P2 = spawn(fun() -> clientloop() end),
        {P1,P2}.
    
    endtest({P1,P2}) ->
        exit(P1,kill),
        exit(P2,kill),
        stop().
    
    posloop(I) ->
        storepos(I),
        timer:sleep(random:uniform(50)),
        posloop(I+1).
    
    clientloop() ->
        io:format("position at ~p is ~p~n",[erlang:now(),getpos()]),
        timer:sleep(random:uniform(200)),
        clientloop().
    

    测试结果:

    1> A = latest:test().
    position at {1399,377773,874000} is 0
    {<0.64.0>,<0.65.0>}
    position at {1399,377773,967000} is 2
    position at {1399,377774,124000} is 6
    position at {1399,377774,327000} is 12
    position at {1399,377774,436000} is 17
    position at {1399,377774,514000} is 19
    position at {1399,377774,639000} is 24
    position at {1399,377774,827000} is 30
    position at {1399,377774,967000} is 34
    position at {1399,377775,77000} is 38
    position at {1399,377775,202000} is 42
    position at {1399,377775,233000} is 43
    position at {1399,377775,280000} is 44
    position at {1399,377775,436000} is 47
    position at {1399,377775,483000} is 48
    position at {1399,377775,608000} is 52
    position at {1399,377775,655000} is 54
    position at {1399,377775,749000} is 57
    position at {1399,377775,842000} is 60
    position at {1399,377775,858000} is empty
    position at {1399,377775,983000} is 63
    position at {1399,377776,92000} is 66
    position at {1399,377776,186000} is 69
    2> latest:endtest(A).
    stop
    3> 
    

    【讨论】:

    • 次要 nitpick:我会在客户端询问其位置后发送调用循环(最后)而不是循环(空),以防客户端在服务器发送另一个更新之前再次询问。
    • 太棒了!我用 Jinterface 代替了它,但使用了你的想法,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 2015-12-16
    • 2020-02-17
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多