Erlang TCP服务器总是在接受时关闭

ldfqzlk8  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(239)

我是Erlang的新手,我正在尝试建立一个简单的多客户端聊天服务器来学习更多关于Erlang的知识。然而,每当我尝试运行它时,我都会收到一个套接字关闭错误,这是由于在侦听套接字上调用gen_tcp:accept造成的。我尝试了许多不同的端口号都没有用。我错过了什么呢?
代码如下:

-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]
2eafrhcq

2eafrhcq1#

这里的问题是ListenSocket的控制器终止,这导致ListenSocket关闭。

相关问题