1

I am writing a game engine in Erlang where the server is constantly sending new positions to the client. I want to just use the latest message and throw the rest away, is there some way I can do that? I am using Jinterface on the client side, so a solution for that would be nice.

rablentain
  • 6,641
  • 13
  • 50
  • 91

1 Answers1

2

In erlang, it is not possible (directly) to do what you say. But you can use an intermediate server to achieve this behavior. the role of this server would be to receive all messages and keep a copy of the latest one, and to answer to a client request by sending this message.

-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().

test result:

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> 
Pascal
  • 13,977
  • 2
  • 24
  • 32
  • Minor nitpick: I would send invoke loop(Last) rather than loop(empty) after the client asks for its location, in case the client asks again before the server sends another update. – macintux May 06 '14 at 13:36
  • Great! I got it working with Jinterface instead but used your idea, thanks! – rablentain May 07 '14 at 06:40