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

The init () function creates a Socket Socket value and returns the 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 a socket in my start () function?

+4
source share
2 answers

If you need the udp function in your start function, you can also create it in the start function and pass it to the original call as a parameter. Thus, you do not need to call the server after it is created.

rvirding indicates that this will cause the initial process to receive messages from the udp socket, rather than from the newly created server. See Comments for more information. It is not clear what exactly is needed for the socket in the start method, but make sure that this is what 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}. 
+1
source

You need to get the socket by creating gen_server:call for the newly created gen_server process. eg:.

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

And in gen_server add something like:

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

Source: https://habr.com/ru/post/1432364/


All Articles