Ranch:
In short, ranch is a TCP acceptor pool used to establish and manage TCP connections in high concurrency. You can set the maximum number of concurrent connections. You can dynamically upgrade the connection pool without closing the socket connection. Cowboy is the ranch used.
Https://github.com/ninenines/ranch
The following describes how to transform the reverse example provided by ranch to implement a simple server.
Game_server.app.src
{application, game_server, [{description, "Ranch TCP reverse example."},{vsn, "1"},{modules, []},{registered, []}, {applications, [kernel,stdlib,ranch]},{mod, {game_server_app, []}},{env, []}]}.
Game_server_app.erl
-module(game_server_app).-behaviour(application).-export([start/2, stop/1]).%% start/2start(_Type, _StartArgs) -> {ok, _Pid} = ranch:start_listener(tcp_reverse, 1, ranch_tcp, [{port, 5555},{max_connections, 10240}], game_protocol, []), game_server_sup:start_link().%% stop/1stop(State) -> ok.
Note ranch: start_listener (ref, nbacceptors, transport, transopts, protocol, protoopts)-> {OK, PID ()} | {error, badarg }.
The maximum number of connections max_connections is set here. The default value is 1024. nbacceptors and the number of acceptor. The specific value must be set based on the actual concurrency.
Ranch accepts the request and establishes a connection, and then delivers the specific processing to the game_protocol that implements the ranch_protocol action. Behaviour in Erlang is similar to that in Java.
Game_server_sup.erl
-module(game_server_sup).-behaviour(supervisor).-export([start_link/0, init/1]).-spec start_link() -> {ok, pid()}.start_link() ->supervisor:start_link({local, ?MODULE}, ?MODULE, []).%% init/1init([]) ->{ok, {{one_for_one, 10, 10}, []}}.
Game_protocol.erl
-module(game_protocol).-behaviour(gen_server).-behaviour(ranch_protocol).%% API.-export([start_link/4]).%% gen_server.-export([init/4]).-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).-define(TIMEOUT, 50000).-record(state, {socket, transport}).%% API.start_link(Ref, Socket, Transport, Opts) -> proc_lib:start_link(?MODULE, init, [Ref, Socket, Transport, Opts]).%% gen_server.%% This function is never called. We only define it so that%% we can use the -behaviour(gen_server) attribute.init([]) -> {ok, undefined}.init(Ref, Socket, Transport, _Opts = []) -> ok = proc_lib:init_ack({ok, self()}), ok = ranch:accept_ack(Ref), ok = Transport:setopts(Socket, [{active, once}, {packet, 2}]), gen_server:enter_loop(?MODULE, [], #state{socket=Socket, transport=Transport}, ?TIMEOUT).handle_info({tcp, Socket, Data}, State=#state{ socket=Socket, transport=Transport}) -> io:format("Data:~p~n", [Data]), Transport:setopts(Socket, [{active, once}]), Transport:send(Socket, reverse_binary(Data)), {noreply, State, ?TIMEOUT};handle_info({tcp_closed, _Socket}, State) -> {stop, normal, State};handle_info({tcp_error, _, Reason}, State) -> {stop, Reason, State};handle_info(timeout, State) -> {stop, normal, State};handle_info(_Info, State) -> {stop, normal, State}.handle_call(_Request, _From, State) -> {reply, ok, State}.handle_cast(_Msg, State) -> {noreply, State}.terminate(_Reason, _State) -> ok.code_change(_OldVsn, State, _Extra) -> {ok, State}.%% Internal.reverse_binary(B) when is_binary(B) -> list_to_binary(lists:reverse(binary_to_list(B))).
The implementation of init is different from that of normal gen_server. First, why can't we use the conventional gen_server syntax. The general syntax is as follows:
init([Ref, Socket, Transport, Opts]) -> ok = ranch:accept_ack(Ref), ok = Transport:setopts(Socket, [{active, once}, {packet, 2}]), {ok, #state{socket=Socket, transport=Transport}}.
Start_link of gen_server will return only after init/1 is executed, but here we can see ranch: accept_ack (REF ):
-spec accept_ack(ref()) -> ok.accept_ack(Ref) -> receive {shoot, Ref, Transport, Socket, AckTimeout} -> Transport:accept_ack(Socket, AckTimeout) end.
When ranch: accept_ack/1 is run, the process will be blocked. Wait for the message {shoot,...} until the message is received, and the init will be completed. But where does the {shoot,...} message come from? Check the ranch source code and find that ranch will send the message to the gen_server process after establishing a connection with the new gen_server process (refer to ranch_conns_sup: loop/4 ). apparently, the gen_server process is waiting for ranch: accept_ack to receive {shoot ,...} the message cannot be returned, but ranch cannot be connected to the gen_server process and cannot be sent {shoot ,...} message, causing a deadlock. Proc_lib: start_link/3 is used to solve this problem elegantly.
The following is a description of the document:
By default the socket will be set to return 'binary 'data, with
Options '{active, false}', '{packet, raw}', '{reuseaddr, true}' set.
These values can't be overriden when starting the listener,
They can be overriden using 'Transport: setopts/2' in the Protocol.
It will also set '{backlog, 1024}' and '{nodelay, true}', which
Can be overriden at listener startup.
That's why {active, once}, {packet, 2} can only be rewritten in procotol
In this way, a basic server is implemented. After making, write the script to start it:
Start. Sh
erl -pa ebin deps/*/ebin +K true +P 199999 -sname game_server -s game
-S game indicates that the game: Start/0 method is called by default at startup.
Game. erl
-module(game).%% ====================================================================%% API functions%% ====================================================================-export([start/0, stop/0]).start() -> ok = application:start(ranch), ok = application:start(game_server).stop() -> application:stop(ranch), application:stop(game_server).
If {packet, raw} is set, you can directly open a terminal $ Telnet localhost 5555 to perform the test.
But here {packet, 2} is set, so a test client is written to send messages, establish a connection-> send messages-> receive returned messages-> close the connection:
-module(client).-export([send/1]).send(BinMsg) -> SomeHostInNet = "localhost", {ok, Sock} = gen_tcp:connect(SomeHostInNet, 5555, [binary, {packet, 2}]), ok = gen_tcp:send(Sock, BinMsg), receive {tcp,Socket,String} -> io:format("Client received = ~p~n",[String]), gen_tcp:close(Socket) after 60000 -> exit end, ok = gen_tcp:close(Sock).
Add processing of different messages to handler_info to make it a simple game server. {Active, n} can be used after R17, and the program efficiency should be higher.