[erlang-questions] multiple process handling one udp listen socket ?

Sergej Jurecko <>
Sat Feb 2 15:44:13 CET 2013


You can't listen on multiple processes. Do you really need all communication through a single port? This is generally not how protocols based on UDP work. 
If you really have to do it, you have to increase receive buffer for it. inet:setopts(Sock,[{recbuf,SomethingBig}]).
Do not do anything other than receive bytes on that socket/process. Open a new process and socket for processing and reply.
{active,true} is not a good idea on that process. False or once are safer options.

Sergej

On Feb 2, 2013, at 3:29 PM, Morgan Segalis wrote:

> Hi everyone,
> 
> I'm scratching my head with a particular problem...
> I would like to create my own udp relay server.
> 
> Right now my udp relay server works fine, but it is only using one process...
> 
> [CODE]
> 
> start_server() ->
>    spawn(?MODULE, sl, [80]).
> 
> sl(Port) ->
>    {ok, Socket} = gen_udp:open(Port, [binary]),
>    inet:setopts(Socket, [{active, true}]),
>    listen(Socket).
> 
> listen(Socket) ->
>    receive
> 	{udp, _ , Host, Port, <<0>>} ->
> 	    io:fwrite("Host: ~p~n", [Host]),
> 	    io:fwrite("DistantPort: ~p~n", [Port]),
> 	    io:fwrite("server received:~p~n",[Socket]),
> 	    io:fwrite("LocalPort: ~p~n", [inet:port(Socket)]),
> 	    Message = lists:flatten(io_lib:format("~p\0", [Port])),
> 	    Res = gen_udp:send(Socket, Host, Port, Message),
> 	    io:fwrite("Sent back: ~p // ~p~n", [Port, Res]),
> 	    listen(Socket);
> 	{udp, _, _, _, <<1:8, 
> 			 Ip1:1/big-unsigned-integer-unit:8, 
> 			 Ip2:1/big-unsigned-integer-unit:8, 
> 			 Ip3:1/big-unsigned-integer-unit:8, 
> 			 Ip4:1/big-unsigned-integer-unit:8, 
> 			 Port1:1/big-unsigned-integer-unit:8,
> 			 Port2:1/big-unsigned-integer-unit:8,
> 			 Bin/binary>>} ->
> 	    Ip = {Ip1, Ip2, Ip3, Ip4},
> 	    Port = Port1 * 256 + Port2,
> 	    gen_udp:send(Socket, Ip, Port, Bin),
> 	    listen(Socket);
> 	Any ->
> 	    listen(Socket)
>    end.
> 
> [/CODE]
> 
> I'm worrying that if multiple (hundred, thousand ?) clients are using it, the process will be overwhelmed...
> Since right now I'm only listening one port (right now 80), I do not seems to see how to make multiple process to handle the same socket. Since udp is quite different from tcp since it does not need to connect/accept connections.
> 
> I would like to know if there is a way to get multiple process to handle the listen socket Even if it means that each process is handling only one client (specific host ?)... The only thing is, that the listen port should be the same for all client...
> 
> Thank you for your help,
> 
> Morgan.
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list