Question

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

Was it helpful?

Solution

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}.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top