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

Dmitry Kolesnikov dmkolesnikov@REDACTED
Mon May 15 13:09:00 CEST 2017


Hello,

You are starting the port in “passive mode” (active = false). 
Try to change  
```
{ok, Socket} = gen_udp:open(Port, [binary, {active, true}, ...]),
```

Best Regards, 
Dmitry



> On May 15, 2017, at 12:27 PM, 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 vote
> favorite
> 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




More information about the erlang-questions mailing list