JeremiahDixon
JeremiahDixon

Reputation: 33

Erlang TCP server always closes on accept

I'm fairly new to Erlang, and I'm trying to set up a simple multi-client chat server to learn more about the language. However whenever I try and run it I get a socket closed error from the call of gen_tcp:accept on the listening socket. I've tried a number of different port numbers to no avail. What am I missing?

The code is below:

-define(TCP_OPTIONS, [binary, {packet, 2}, {active, false}, {reuseaddr, true}]).

listen(Portno, DictPid) -> 
  case gen_tcp:listen(Portno, ?TCP_OPTIONS) of
    {ok, ListenSocket} ->
      spawn_link(fun() -> accept_connections(ListenSocket, DictPid) end),
      io:format("Listening on ~p~n", [ListenSocket]);
    {error, Error} ->
      io:format("Listen Error: ~w~n", [Error])
  end.

accept_connections(ListenSocket, DictPid) ->
  case gen_tcp:accept(ListenSocket) of
    {ok, ClientSocket} ->
      io:format("Accepting:~w~n", [ClientSocket]),
      gen_tcp:send(ClientSocket, "Welcome! Enter your name~n"),
      ClientPid = spawn(fun() -> io:format("Client connected"),
                                 setup_user(ClientSocket, DictPid) end),
      gen_tcp:controlling_process(ClientSocket, ClientPid),
      accept_connections(ListenSocket, DictPid);
    {error, Error} ->
      io:format("Accept Error: ~w~n", [Error])
  end.
  
setup_user(ClientSocket, DictPid) ->
  {ok, Username} = gen_tcp:recv(ClientSocket, 0),
  DictPid ! {add_new_pair, ClientSocket, Username},
  ClientDict = get_dict(DictPid),
  broadcast_message(dict:fetch_keys(ClientDict), "[" ++ Username ++ "has entered the chat]"),
  client_loop(ClientSocket, Username, DictPid).

[rest of program]

Upvotes: 1

Views: 77

Answers (1)

José M
José M

Reputation: 3509

The issue here is that the controller of the ListenSocket terminates, which causes the ListenSocket to be closed.

Upvotes: 2

Related Questions