erlang学习: erlang版echoserver

erlang实现的简单的echo server
采用每连接对应一个进程的模式
用到了 gen_tcp 模块、erlang的消息接收模型

-module(echoserver).

-export([start/0, stop/0, server/0, handle_connect/3]).

start() ->
    % 创建一个进程,运行 server()
    register(echoserver, spawn(?MODULE, server, [])).

stop() ->
    echoserver ! {quit}.

server() ->
    {ok, ListenSocket} = gen_tcp:listen(12345, [binary, {reuseaddr, true}, {active, false}]),
    loop(ListenSocket, 0). 

loop(ListenSocket, Count) ->
    receive
        {quit} ->
            io:format("echoserver will stop~n"),
            gen_tcp:close(ListenSocket);
        Reason ->
            io:format("recv ~p~n", Reason)
    after 10 ->  
         % 等待连接
         case gen_tcp:accept(ListenSocket, 3000) of
            {ok, Socket} ->
                % 创建一个进程来处理此连接
                spawn(?MODULE, handle_connect, [Socket, [], Count]),
                loop(ListenSocket, Count+1);
            {error, timeout} ->
                loop(ListenSocket, Count);
            {error, Reason} ->
                io:format("accept failed~n"),
                gen_tcp:close(ListenSocket)
        end 
    end.

handle_connect(Socket, BinaryList, Count) ->
    io:format("handle_connect ~p~n", [self()]),
    case gen_tcp:recv(Socket, 0) of
        {ok, Binary} ->
            case gen_tcp:send(Socket, Binary) of
                ok ->
                    handle_connect(Socket, BinaryList, Count);
                {error, Reason} ->
                    io:format("send failed~n"),
                    gen_tcp:close(Socket)
            end;
        {error, timeout} ->
            io:format("recv timeout~n"),
            gen_tcp:close(Socket);
        {error, closed} ->
            gen_tcp:close(Socket)
    end.

你可能感兴趣的:(erlang)