【问题标题】:Erlang TCP server always closes on acceptErlang TCP 服务器总是在接受时关闭
【发布时间】:2021-03-14 04:09:31
【问题描述】:

我是 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]

【问题讨论】:

  • 您可能希望从文档 https://erlang.org/doc/man/gen_tcp.html#examples 中的 gen_tcp 示例开始

标签: tcp network-programming erlang


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 2021-02-19
    • 2015-12-07
    • 2019-04-30
    • 2023-03-07
    • 2015-09-04
    • 2015-04-14
    • 2020-09-17
    相关资源
    最近更新 更多