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

Morgan Segalis msegalis@REDACTED
Sat Feb 2 15:29:54 CET 2013


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.


More information about the erlang-questions mailing list