kai_tcp_server: a simple module for implementing concurrent TCP servers

Last July, Kai developer team made a simple module named "kai_tcp_server", which has the following features:

  • Makes it easy to implement concurrent TCP servers,
  • Provides typical TCP server behaviours, listen, accept, and so forth,
  • Handles multiple requests concurrently by maintaining process pool,
  • Supports active as well as passive mode of gen_tcp,
  • Based on OTP principles.

How to Use

The following code of module provides a simple example of a echo server.

-module(echo).
-behaviour(kai_tcp_server).

-export([start_link/0, stop/0]).
-export([init/1, handle_call/3]).

-include("kai.hrl").

%% I/F
start_link() ->
    kai_tcp_server:start_link(
        ?MODULE, [], #tcp_server_option{port = 10000, max_processes = 2}
    ).

stop() ->
    kai_tcp_server:stop().

%% Callbacks
init(_Args) ->
    {ok, {}}.

handle_call(_Socket, <<"bye\r\n">>, State) ->
    {close, <<"cya\r\n">>, State};
handle_call(_Socket, Data, State) ->
    {reply, Data, State}.

This server is listening on port 10000 and accepts the two connections or less at the same time.

For more examples, see the following links.

Process Design

This module include a supervisor process with one_for_one restart strategy and several child process for socket accepting.

   +-------------------------+
   | tcp_server (supervisor) |
   +------------+------------+
                | (one_for_one)
   +------------|-----------------+
 +--------------|----------------+|
+---------------+---------------+|+
| acceptor (made from proc_lib) |+
+-------------------------------+

Download

Please download the latest version from the Kai subversion repository on Sourceforge.

Maybe this module is separated from the Kai if there is someone's hope.