[erlang-questions] Erlang udp server can't receive accept packets

Steve Strong steve@REDACTED
Mon May 15 14:01:14 CEST 2017


As well as the replies talking about ‘active, false’, you are also opening the socket before starting the gen_server - so any messages received by the socket would go to the mailbox of the process that called start_link, rather than the gen_server process.  Suspect you near to do the gen_udp:open inside init/1

Cheers,

Steve

On 15 May 2017, 12:03 +0100, yuzhu chen <billcyz@REDACTED>, wrote:
> I've posted the same question on stackoverflow, but haven't got answers yet. So I posted this question again in here hoping for a solution.
>
>
>
> down votefavorite
> I have one simple udp server written in gen_server behaviour. When I run it, and try to send message by using gen_udp:send, the server replies nothing, seems like the udp server didn't accept packet successfully. Here is my code
> gen_udp_server.erl:
>
> -module(gen_udp_server).
> -behaviour(gen_server).
> -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
>
> -export([start_link/1]).
>
> -define(SERVER, ?MODULE).
>
> -record(state, {socket,
>                port,
>                local_ip,
>                broad_ip}).
>
> start_link(Port) ->
>    {ok, Socket} = gen_udp:open(Port, [binary,
>                                       {active, false},
>                                       {reuseaddr, true}]),
>    gen_server:start_link(?MODULE, [Socket, Port], []).
>
> init([Socket, Port]) ->
>    {ok, #state{socket = Socket, port = Port}}.
>
> handle_cast(_Request, State) ->
>    {noreply, State}.
>
> handle_call(_Request, _From, State) ->
>    {noreply, State}.
>
> handle_info({udp, _Socket, _Addr, _Port, Data}, #state{socket = Socket} = State) ->
>    inet:setopts(Socket, [{active, once}]),
>    io:format("Server received data ~p from socket ~p~n", [Data, Socket]),
>    {ok, State}.
>
> terminate(_Reason, {socket = LSocket}) ->
>    gen_udp:close(LSocket).
>
> code_change(_OldVsn, State, _Extra) ->
>    {ok, State}.
> Starting server on server 192.168.146.129: gen_udp_server:start_link(10000).
> Sending message from 192.168.146.128:
>
> {ok, Socket} = gen_udp:open(4399, [binary, {active, false}]).
> gen_udp:send(Socket, {192,168,146,129}, 10000, "hello").
> The udp server should print some message when it receives packets, but my one failed. Can anyone help me?
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20170515/5b0d6b7c/attachment.htm>


More information about the erlang-questions mailing list