Blog.csdn.net/mycwq/artic…

blog.csdn.net/mycwq\

Complete source code download address: download.csdn.net/download/li… \

Erlang OTP builds a TCP server based on Erlang OTP, which describes the implementation method of two hybrid sockets. It is really exciting to see the article. Building a non-blocking TCP server using OTP principles Combining these two articles, this article continues to discuss the concrete implementation of Erlang/OTP building TCP servers with examples of how to create a simple non-blocking TCP server using standard Erlang/OTP behavior.

The TCP Socket model

Active mode {active, true}, non-blocking way receives the message, but it cannot cope with large flow system request, the client sends the data too fast, and more than the speed of the server can handle, then, the system may lead to a message buffer is full, persistent, busy traffic extreme situation, system due to request too much overflow, Erlang virtual machine crashes due to insufficient memory. Passive mode {active, false}, blocking mode to receive messages, the underlying TCP buffer can be used to suppress the request, and reject the client message, in the place of receiving data will call gen_TCP :recv, causing blocking (in single-process mode can only passively wait for a specific client Socket, It’s dangerous. It is important to note that the operating system may also do some caching to allow the client machine to continue sending a small amount of data before blocking it, but Erlang has not yet called the recV function. Mixed mode (semi-blocking, {active, once}), active Socket for one message only, after the control process has sent a message data, it must explicitly call inet:setopts(Socket, [{active, once}]) to reactivate in order to receive the next message (before this, The system is blocked. It can be seen that the hybrid mode combines the advantages of both active mode and passive mode to realize traffic control and prevent the server from being overwhelmed by too many messages. So if you want to build a TCP server, it makes sense to build on the TCP Socket hybrid mode (semi-blocking). \

TCP Server Design

The design of the TCP server includes the main application tcp_server_app and the supervisor tcp_server_sup process, which has two child processes tcp_server_listener and tcp_client_sup. The tcp_server_listener handles the connection request from the client and tells the TCP_client_sup to start a tcp_server_handler instance process to handle a client request. The instance process then handles the server-client interaction data. \

\

Application and monitoring behavior

To build an Erlang/OTP application, we need to build some modules to implement the application and monitor the behavior. When the application starts, tcp_server_app:start/2 calls tcp_server_sup:start_link/1 to create the master supervisor process. The supervisor instantiates the child worker process tcp_server_listener and the child supervisor process tcp_client_sup by calling back tcp_server_sup:init/1. The subsupervisor calls back to tcp_server_sup:init/1 to instantiate the worker process tcp_server_handler, which is responsible for handling client connections. \

TCP server application (tcp_server_app.erl)

[plain]  view plain  copy

  1. -module(tcp_server_app).  
  2. -behaviour(application).  
  3. -export([start/2, stop/1]).  
  4. -define(PORT,  2222).  
  5.   
  6. start(_Type, _Args) ->  
  7.   io:format(“tcp app start~n”),  
  8. case tcp_server_sup:start_link(? PORT) of
  9.     {ok, Pid} ->  
  10.       {ok, Pid};  
  11.     Other ->  
  12.       {error, Other}  
  13.   end.  
  14.   
  15. stop(_S) ->  
  16.   ok.  

TCP server supervisor process (tcp_server_sup.erl)

[plain]  view plain  copy

  1. -module(tcp_server_sup).  
  2. -behaviour(supervisor).  
  3. -export([start_link/1, start_child/1]).  
  4. -export([init/1]).  
  5.   
  6. start_link(Port) ->  
  7.   io:format(“tcp sup start link~n”),  
  8. supervisor:start_link({local, ? MODULE}, ? MODULE, [Port]).
  9.   
  10. start_child(LSock) ->  
  11.   io:format(“tcp sup start child~n”),  
  12.   supervisor:start_child(tcp_client_sup, [LSock]).  
  13.   
  14. init([tcp_client_sup]) ->  
  15.   io:format(“tcp sup init client~n”),  
  16.   {ok,  
  17.    { {simple_one_for_one, 0, 1},  
  18.     [  
  19.      { tcp_server_handler,   
  20.       {tcp_server_handler, start_link, []},  
  21.       temporary,   
  22.       brutal_kill,   
  23.       worker,   
  24.       [tcp_server_handler]  
  25.      }  
  26.     ]  
  27.    }  
  28.   };  
  29.   
  30. init([Port]) ->  
  31.   io:format(“tcp sup init~n”),  
  32.   {ok,  
  33.     { {one_for_one, 5, 60},  
  34.      [  
  35.       % client supervisor  
  36.      { tcp_client_sup,   
  37.       {supervisor, start_link, [{local, tcp_client_sup}, ?MODULE, [tcp_client_sup]]},  
  38.       permanent,   
  39. In 2000,
  40.       supervisor,   
  41.       [tcp_server_listener]  
  42.      },  
  43.      % tcp listener  
  44.      { tcp_server_listener,   
  45.       {tcp_server_listener, start_link, [Port]},  
  46.       permanent,   
  47. In 2000,
  48.       worker,   
  49.       [tcp_server_listener]  
  50.      }  
  51.     ]  
  52.    }  
  53.   }.  

TCP server Socket listener process (tcp_server_listener.erl) \

[plain]  view plain  copy

  1. -module(tcp_server_listener).  
  2. -behaviour(gen_server).  
  3. -export([start_link/1]).  
  4. -export([init/1, handle_call/3, handle_cast/2, handle_info/2,  
  5.          terminate/2, code_change/3]).  
  6. -record(state, {lsock}).  
  7.   
  8. start_link(Port) ->  
  9.   io:format(“tcp server listener start ~n”),  
  10. gen_server:start_link({local, ? MODULE}, ? MODULE, [Port], []).
  11.   
  12. init([Port]) ->  
  13.   process_flag(trap_exit, true),  
  14.   Opts = [binary, {packet, 0}, {reuseaddr, true},  
  15.            {keepalive, true}, {backlog, 30}, {active, false}],  
  16.   State =  
  17.   case gen_tcp:listen(Port, Opts) of  
  18.     {ok, LSock} ->  
  19.       start_server_listener(LSock),  
  20.       #state{lsock = LSock};  
  21.     _Other ->  
  22.       throw({error, {could_not_listen_on_port, Port}}),  
  23.       #state{}  
  24.   end,  
  25.     {ok, State}.  
  26.   
  27. handle_call(_Request, _From, State) ->  
  28.   io:format(“tcp server listener call ~p~n”, [_Request]),  
  29.   {reply, ok, State}.  
  30.   
  31. handle_cast({tcp_accept, Pid}, State) ->  
  32.   io:format(“tcp server listener cast ~p~n”, [tcp_accept]),  
  33.   start_server_listener(State, Pid),  
  34.     {noreply, State};  
  35.   
  36. handle_cast(_Msg, State) ->  
  37.   io:format(“tcp server listener cast ~p~n”, [_Msg]),  
  38.   {noreply, State}.  
  39.   
  40. handle_info({‘EXIT’, Pid, _}, State) ->  
  41.   io:format(“tcp server listener info exit ~p~n”, [Pid]),  
  42.   start_server_listener(State, Pid),  
  43.   {noreply, State};  
  44.   
  45. handle_info(_Info, State) ->  
  46.   io:format(“tcp server listener info ~p~n”, [_Info]),  
  47.   {noreply, State}.  
  48.   
  49. terminate(_Reason, _State) ->  
  50.   io:format(“tcp server listener terminate ~p~n”, [_Reason]),  
  51.   ok.  
  52.   
  53. code_change(_OldVsn, State, _Extra) ->  
  54.   {ok, State}.  
  55.   
  56. start_server_listener(State, Pid) ->  
  57.   unlink(Pid),  
  58.   start_server_listener(State#state.lsock).  
  59.   
  60. start_server_listener(Lsock) ->  
  61.   case tcp_server_sup:start_child(Lsock) of  
  62.     {ok, Pid} ->  
  63.       link(Pid);  
  64.     _Other ->  
  65.       do_log  
  66.   end.  

The TCP server handles the client request process (tcp_server_handler.erl) \

[plain]  view plain  copy

  1. -module(tcp_server_handler).  
  2. -behaviour(gen_server).  
  3. -export([start_link/1]).  
  4. -export([init/1, handle_call/3, handle_cast/2, handle_info/2,  
  5.          terminate/2, code_change/3]).  
  6. -record(state, {lsock, socket, addr}).  
  7. -define(Timeout, 120*1000).  
  8.   
  9. start_link(LSock) ->  
  10.   io:format(“tcp handler start link~n”),  
  11. gen_server:start_link(? MODULE, [LSock], []).
  12.   
  13. init([LSock]) ->  
  14.   io:format(“tcp handler init ~n”),  
  15.   inet:setopts(LSock, [{active, once}]),  
  16.   gen_server:cast(self(), tcp_accept),  
  17.   {ok, #state{lsock = LSock}}.  
  18.   
  19. handle_call(Msg, _From, State) ->  
  20.   io:format(“tcp handler call ~p~n”, [Msg]),  
  21.   {reply, {ok, Msg}, State}.  
  22.   
  23. handle_cast(tcp_accept, #state{lsock = LSock} = State) ->  
  24.   {ok, CSock} = gen_tcp:accept(LSock),  
  25.   io:format(“tcp handler info accept client ~p~n”, [CSock]),  
  26.   {ok, {IP, _Port}} = inet:peername(CSock),  
  27.    start_server_listener(self()),  
  28. {noreply, State#state{socket=CSock, addr=IP}, ? Timeout};
  29.   
  30. handle_cast(stop, State) ->  
  31.   {stop, normal, State}.  
  32.   
  33. handle_info({tcp, Socket, Data}, State) ->  
  34.   inet:setopts(Socket, [{active, once}]),  
  35.   io:format(“tcp handler info ~p got message ~p~n”, [self(), Data]),  
  36.   ok = gen_tcp:send(Socket, <<Data/binary>>),  
  37. {noreply, State, ? Timeout};
  38.   
  39. handle_info({tcp_closed, _Socket}, #state{addr=Addr} = State) ->  
  40.   io:format(“tcp handler info ~p client ~p disconnected~n”, [self(), Addr]),  
  41.   {stop, normal, State};  
  42.   
  43. handle_info(timeout, State) ->  
  44.   io:format(“tcp handler info ~p client connection timeout~n”, [self()]),  
  45.   {stop, normal, State};  
  46.   
  47. handle_info(_Info, State) ->  
  48.   io:format(“tcp handler info ingore ~p~n”, [_Info]),  
  49.   {noreply, State}.  
  50.    
  51. terminate(_Reason, #state{socket=Socket}) ->  
  52.   io:format(“tcp handler terminate ~p~n”, [_Reason]),  
  53.   (catch gen_tcp:close(Socket)),  
  54.   ok.  
  55.   
  56. code_change(_OldVsn, State, _Extra) ->  
  57.   {ok, State}.  
  58.   
  59. start_server_listener(Pid) ->  
  60.   gen_server:cast(tcp_server_listener, {tcp_accept, Pid}).  

TCP server resource file (tcp_server.app) \

[plain]  view plain  copy

  1. {application,tcp_server,  
  2.   [{description,”TCP Server”},  
  3. {VSN, “1.0.0”},
  4.    {modules,[tcp_server,tcp_server_app,tcp_server_handler,  
  5.          tcp_server_listener,tcp_server_sup]},  
  6.    {registered,[]},  
  7.    {mod,{tcp_server_app,[]}},  
  8.    {env,[]},  
  9.    {applications,[kernel,stdlib]}]}.  

compiler

Create the following directory structure for your application:

[plain]  view plain  copy

  1. ./tcp_server  
  2. ./tcp_server/ebin/  
  3. ./tcp_server/ebin/tcp_server.app  
  4. ./tcp_server/src/tcp_server_app.erl  
  5. ./tcp_server/src/tcp_server_sup.erl  
  6. ./tcp_server/src/tcp_server_listener.erl  
  7. ./tcp_server/src/tcp_server_handler.erl  

Linux:

[plain]  view plain  copy

  1. $ cd tcp_server/src  
  2. $ for f in tcp*.erl ; do erlc -o .. /ebin $f
  3. Seems to not work, please use: erlc-O.. /ebin *.erl\

Windows, CMD enter, remember to add environment variables to erL OTP path :\

[plain]  view plain  copy

  1. cd tcp_server/src  
  2. for %i in (tcp*.erl) do erlc -o .. /ebin %i

To run the program

1. Start the TCP server

[plain]  view plain  copy

  1. erl -pa ebin  
  2. .
  3. 1> application:start(tcp_server).  
  4. tcp app start  
  5. tcp sup start link  
  6. tcp sup init  
  7. tcp sup init client  
  8. tcp server listener start  
  9. tcp sup start child  
  10. tcp handler start link  
  11. tcp handler init  
  12. ok  
  13. 2> appmon:start().  
  14. {ok, < 0.41.0 >}

\

Note that appmon appears to be an observer after ERl17. So if you can’t start appmon:start(), try observer:start().

Create a client to request the TCP server:

[plain]  view plain  copy

  1. 3 > f (S),} {ok, S = gen_tcp: connect (,0,0,1 {127}, 2222, [{0} packet,]).
  2. {ok, # Port < 0.1859 >}
  3. TCP handler info Accept client #Port<0.1860>
  4. tcp server listener cast tcp_accept  
  5. tcp sup start child  
  6. tcp handler start link  
  7. tcp handler init  

Send a message to the server using this request:

[plain]  view plain  copy

  1. 4> gen_tcp:send(S,<<“hello”>>).  
  2. ok  
  3. TCP Handler Info <0.53.0> got Message <<“hello”>>

4. Receiving the message from the server: \

[plain]  view plain  copy

  1. 5> f(M), receive M -> M end.  
  2. {the TCP, # Port < 0.1861 >, “hello”}

5. Now let’s try sending multiple connection requests to the server: \

[plain]  view plain  copy

  1. 6 > gen_tcp: connect (,0,0,1 {127}, 2222, [{0} packet,]).
  2. .
  3. 7 > gen_tcp: connect (,0,0,1 {127}, 2222, [{0} packet,]).
  4. .
  5. 8 > gen_tcp: connect (,0,0,1 {127}, 2222, [{0} packet,]).
  6. .



\

6. The server program has a timeout function. If there is no operation within 2 minutes, the connection will automatically exit

[plain]  view plain  copy

  1. 9> tcp handler info <0.39.0> client connection timeout  
  2. 9> tcp handler terminate normal  
  3. 9> tcp handler info <0.52.0> client connection timeout  
  4. 9> tcp handler terminate normal  
  5. 9> tcp handler info <0.54.0> client connection timeout  
  6. 9> tcp handler terminate normal  
  7. 9> tcp handler info <0.56.0> client connection timeout  
  8. 9> tcp handler terminate normal  

\

7. Let’s briefly demonstrate the monitoring behavior of the server:

[plain]  view plain  copy

  1. 9 > exit (pid (0,58,0), kill).
  2. TCP Server listener info exit <0.58.0>
  3. true  
  4. tcp sup start child  
  5. tcp handler start link  
  6. tcp handler init  

\

conclusion

This example demonstrates how to create a simple non-blocking TCP server and how to use the standard Erlang/OTP behavior. As an exercise, the reader is encouraged to try abstracting the generic non-blocking TCP server functionality into a stand-alone behavior.

\

Complete source code download address: download.csdn.net/download/li…