Majid Azimi
Majid Azimi

Reputation: 5745

Writing parallel TCP server in erlang

"Programming Erlang Software for a Concurrent World" says to write a parallel TCP server do like this:

start_parallel_server() ->
    {ok, Listen} = gen_tcp:listen(...),
    spawn(fun() -> par_connect(Listen) end).

par_connect(Listen) ->
    {ok, Socket} = gen_tcp:accept(Listen),
    spawn(fun() -> par_connect(Listen) end),
    loop(Socket).

loop(...) -> %% handle request here

When start_parallel_server finishes its work it will close listen socket. Shouldn't we add something like timer:sleep(infinity) at the end of it?

Upvotes: 2

Views: 548

Answers (2)

Elzor
Elzor

Reputation: 804

Moreover, for real world applications https://github.com/extend/ranch is more suitable.

Upvotes: 3

johlo
johlo

Reputation: 5500

If you run start_parallel_server() from the shell the shell process will own the listening socket, so it will stay alive as long as that shell process is alive. Note that the shell process dies on exceptions and a new shell process is respawned… Can cause confusion.

But if you e.g. spawn a new process that in turn calls the start_parallel_server() function you will need a sleep in that spawned process to keep it alive.

Upvotes: 4

Related Questions