Myles McDonnell
Myles McDonnell

Reputation: 13335

Erlang TCP Server - Hybrid Socket Model

I am attempting to implement a hybrid (active/passive) socket model TCP server in Erlang:

%%%-------------------------------------------------------------------
%%% @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.

However, the call to reset the socket to active (inet:setops(Socket, [{active, once}]),) fails with the following:

=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}]}]}

I'm following Programming Erlang 2.0 Chp17. Is the problem related to the preceding line that sends on the same socket?

Upvotes: 0

Views: 147

Answers (1)

legoscia
legoscia

Reputation: 41568

It's inet:setopts/2, not inet:setops/2. undef means that there is no such function, or that it is not exported.

Upvotes: 2

Related Questions