[erlang-questions] how to limit number of connections to gen_tcp?

Jarrod Roberson <>
Tue May 26 19:09:01 CEST 2009


I have the following code. How do I limit the number of connected clients.

-module(linereceiver).

-export([start/0]).

sleep(T) ->
    receive
       after T ->
           true
    end.

start() ->
    spawn(fun() ->
            start_parallel_server(3000),
            sleep(infinity)
          end).

start_parallel_server(Port) ->
    {ok, Listen} = gen_tcp:listen(Port, [binary,
{packet,line},{reuseaddr, true},{active, true}]),
    spawn(fun() -> par_connect(Listen)end).

par_connect(Listen) ->
    {ok, Socket} = gen_tcp:accept(Listen),
    spawn(fun() -> par_connect(Listen) end),
    inet:setopts(Socket, [{packet, line}, list, {nodelay, true},
{active, true}]),
    io:format("Connection Made!~n"),
    get_line(Socket).

get_line(Socket) ->
    receive
        {tcp, Socket, Line} ->
            io:format("Received Line:~p~n", [Line]),
            get_line(Socket);
        {tcp_closed, Socket} ->
            io:format("Connection Closed!~n"),
            void
    end.



More information about the erlang-questions mailing list