Atlas
Atlas

Reputation: 199

Erlang: how to get result from init() in gen_server

My init() function creates UDP Socket and Returns Socket value as a State.

start() ->
        {ok, ServerPid} = gen_server:start_link(?MODULE, [], []).

%%% gen_server API

init([]) ->
        {ok, Socket} = gen_udp:open(8888, [list, {active,false}]),
        {ok, Socket}.

How can I get Socket in my function start()?

Upvotes: 4

Views: 788

Answers (2)

kjw0188
kjw0188

Reputation: 3685

If you need the udp socket int your start function, you can also create it in the start function, and pass it to the start link call as a parameter. That way you don't have to call the server after you created it.

rvirding points out that this will cause the starting process to receive messages from the udp socket, not the newly spawned server. See the comments for more information. It's not clear from the question what exactly the socket is needed for in the start method, but make sure this is the behavior you want.

start() ->
    {ok, Socket} = gen_udp:open(8888, [list, {active,false}]),
    {ok, ServerPid} = gen_server:start_link(?MODULE, Socket, []).

%%% gen_server API

init(Socket) ->
    {ok, Socket}.

Upvotes: 1

johlo
johlo

Reputation: 5500

You need to fetch the socket by making a gen_server:call to the newly created gen_server process. e.g.:

start() ->
        {ok, ServerPid} = gen_server:start_link(?MODULE, [], []),
        Socket = gen_server:call(ServerPid, fetch_socket),
        ... Use Socket ...

And in the gen_server add something like:

handle_call(fetch_socket, _From, State) ->
   {reply, State, State}. %% State == Socket

Upvotes: 6

Related Questions