-module(myserver).
-behaviour(gen_server).
%%define
-define(POLICY_PORT,8080). %%监听端口
-define(TCP_OPTION,[
binary,
{packet,0},
{active,false},
{reuseaddr, true}
]).
%% ====================================================================
%% API functions
%% ====================================================================
-export([start_link/0,start_server/0,loop/1,sendMSG/2,test_info/0,stop/0]).
%%%gen_server callback
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
init([])->
process_flag(trap_exit, true),
%%{ok, test_info()}.
start_server().
handle_call({data,_Data,_PID},_From,_State)->
io:format("call~p~n",[_Data]),
Reply = _Data,
sendMSG(_Data,_PID),
{reply,Reply,_State};
handle_call(_Request,_From,_State)->
Reply = ok,
{reply,Reply,_State}.
handle_cast(stop,State) ->
{stop,normal,State};
handle_cast(_Msg,_State) ->
{noreply,_State}.
handle_info({'_EXIT',_Pid,_Reason},_State)->
io:format("quit...~p~n",[_Pid]),
{noreply,_State};
handle_info({data,_Data,_CSock},_State) ->
case gen_tcp:send(_CSock,_Data) of
ok ->
io:format("client MSG = ~p~n",[_Data]);
{error,Reason} ->
io:format("client Error~p~n",[Reason])
end,
{noreply,_State};
handle_info({tcp_closed,Socket},State)->
io:format("client sockt closed ~p~n",[Socket]),
{noreply,State};
handle_info(_Info,_State) ->
{noreply,_State}.
terminate(_Reason,_State) ->
io:format("I'm terminate.........~n"),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% ====================================================================
%% Internal functions
%% ====================================================================
start_link() ->
io:format("~p start..~n",[self()]),
gen_server:start_link({local,?MODULE}, ?MODULE, [], []).
start_server() ->
case gen_tcp:listen(?POLICY_PORT, ?TCP_OPTION) of
{ok,LSock} ->
%%io:format("listen ok~p~n", []),
spawn(?MODULE,loop,[LSock]),
{ok,LSock};
{error,Reason} ->
{stop,Reason}
end.
loop(LSock) ->
case gen_tcp:accept(LSock) of
{ok,CSock} ->
get_Recv(CSock);
%%{ok,CSock};
{error,Reason} ->
Reason
end,
loop(LSock).
get_Recv(CSock) ->
case gen_tcp:recv(CSock, 0) of
{ok,Data} ->
io:format("get receive ~p~n", [Data]),
%%gen_tcp:send(CSock, Data), %%éç¨gen_server call
gen_server:call(?MODULE,{data,Data,CSock}),
%%gen_server:call(CSock,{data,Data}),
get_Recv(CSock);
_->
error
end.
sendMSG(Data,PID) ->
self()!{data,Data,PID}.
test_info()->
io:format("~p~n", [self()]).
%%通过这种方式正常调用 关闭进程
stop() ->
gen_server:cast(?MODULE,stop).
%%监控进程-module(myserver_sup).
-behaviour(supervisor).
-export([start_link/0]).-export([init/1]).init([]) -> AChild = {myserver,{myserver,start_link,[]}, permanent,2000,worker,[myserver]}, {ok,{{one_for_one,10,10}, [AChild]}}.start_link() ->supervisor:start_link({local,?MODULE},?MODULE,[]).
补充:supervisor资料