当前位置: 动力学知识库 > 问答 > 编程问答 >

erlang - How to call a unique registered gen_server process?

问题描述:

I'm new to Erlang and I'm trying to build a simple game server (learning purpose).

I have one client controller (supervisor) that creates multiple client handlers (gen_server). I have also one game controller (supervisor) that creates multiple game handlers (gen_server).

One game handler (game table) will then communicate with several client handlers (players). I create the client handlers like this:

client_handler.erl:

 start_link(ClientId, UniqueId) ->

ClientHandlerId = utils:create_id(?MODULE, UniqueId), //client_handler_0

State = #state{client_id = ClientId, client_handler_id = ClientHandlerId},

gen_server:start_link({global, ClientHandlerId}, ?MODULE, State, []).

game_handler.erl:

 start_link(ClientHandlerId, GameId, UniqueId) ->

GameHandlerId = utils:create_id(?MODULE, UniqueId), //game_handler_0

State = #state{client_handler_id = ClientHandlerId, game_id = GameId, game_handler_id = GameHandlerId},

gen_server:start_link({global, GameHandlerId}, ?MODULE, State, []).

My problem is that I want to talk between client_handler and game_handler without neither of them knowing about their inner structure. For now I use:

client_handler.erl:

 gen_server:cast(game_handler_0, {make_move, MoveData}).

and this works great. However, I would like to use:

client_handler.erl:

 game_handler_0:make_move(MoveData)

So I can build separate API:s for each module (only use -export functions). Is this possible?

Best regards,

xqtr

EDIT: typo

网友答案:

Yes, it is considered good practice to abstract away implementation details in that way. Just move the cast call into a function in game_handler.erl, something like:

make_move(UniqueId, MoveData) ->
    GameHandlerId = utils:create_id(?MODULE, UniqueId),
    gen_server:cast(GameHandlerId, {make_move, MoveData}).

and export make_move/2. (Or perhaps forget about UniqueId, and pass GameHandlerId directly to the make_move function.)

分享给朋友:
您可能感兴趣的文章:
随机阅读: