erlang學習: erlang版echoserver

iteye_3653發表於2011-09-29
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.

相關文章