Erlang TCP服务器 - 混合套接字模型

时间:2015-02-04 16:33:17

标签: sockets tcp erlang

我正在尝试在Erlang中实现混合(主动/被动)套接字模型TCP服务器:

%%%-------------------------------------------------------------------
%%% @author mylesmcdonnell
%%% @copyright (C) 2015, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 04. Feb 2015 14:01
%%%-------------------------------------------------------------------
-module(mmkvstore_srv).
-author("mylesmcdonnell").

%% API
-export([start/1]).

start(Port) ->
  {ok, Listen} = gen_tcp:listen(Port, [binary, {packet, 4}, {reuseaddr, true}, {active, once} ]),
  spawn(fun() -> connect(Listen) end).

connect(Listen) ->
  io:format("Waiting for connection~n"),
  {ok, Socket} = gen_tcp:accept(Listen),
  io:format("Connection accepted~n"),
  spawn(fun() -> connect(Listen) end),
  loop(Socket).

loop(Socket) ->
  receive
    {tcp, Socket, Bin} ->
      io:format("Server msg rcvd~n"),
      gen_tcp:send(Socket, Bin),
      inet:setops(Socket, [{active, once}]),
      loop(Socket);
    {tcp_closed, Socket} ->
      io:format("Socket closed~n");
    _ ->
      io:format("Unmatched message rcvd ~n")
  end.

但是,将套接字重置为活动的调用(inet:setops(套接字,[{active,once}]))会失败,并显示以下内容:

=ERROR REPORT==== 4-Feb-2015::16:25:24 ===
Error in process <0.156.0> with exit value: {undef,[{inet,setops,[#Port<0.2581>,[{active,once}]],[]},{mmkvstore_srv,loop,1,[{file,"mmkvstore_srv.erl"},{line,34}]}]}

我正在关注编程Erlang 2.0 Chp17。问题是与前一行在同一个套接字上发送有关吗?

1 个答案:

答案 0 :(得分:2)

它是inet:setopts/2,而不是inet:setops/2undef表示没有这样的功能,或者它没有被导出。