lib_chan 简化版

我觉得那个lib_chan太烦,用法我也觉得不那么清晰,反正我不喜欢。
我把它改了改,其实完全不一样,就是中间人的协议类似。
这样我觉得用起来舒服些。

-module(mm).
-compile(export_all).

client_start(Address,Port,Pid) ->
	spawn(fun() ->connect(Address,Port,Pid) end).
	
connect(Address,Port,Pid) ->
	{ok,Socket}=gen_tcp:connect(Address,Port,[binary,{packet,4}]),
	loop(Socket,Pid).
	
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

server_start(Port,Pid) ->
	spawn(fun() ->start_parallel_server(Port,Pid) end),
	ok.

start_parallel_server(Port,Pid) ->
	link(Pid), %% Pid死的时候,listen也得死
	{ok,Listen}=gen_tcp:listen(Port,[binary,{reuseaddr,true},{packet,4},{active,true}]),
	spawn(fun()->par_connect(Listen,Pid) end),
	%% just waiting
	receive
	after infinity ->
		true
	end.
	
par_connect(Listen,Pid) ->
	case gen_tcp:accept(Listen) of
		{ok,Socket} ->
			spawn(fun()->par_connect(Listen,Pid) end),%% 启动一个新进程来accept连接,当前进程处理接受的socket
			link(Pid), %% Pid死的时候,mm也得死(当前进程变成了mm)
			loop(Socket,Pid);
		{error,closed} ->
			io:format("Listenning accept socket error,and was closed!~n")
	end.
	
loop(Socket,Pid) ->
	receive
		{tcp,Socket,Data} ->
			Term=binary_to_term(Data),
			Pid ! {mm,self(),Term},
			loop(Socket,Pid);
		{tcp_closed,Socket} ->
			Pid !{mm_closed,self()};
		{send,Term} ->
			gen_tcp:send(Socket,term_to_binary(Term)),
			loop(Socket,Pid);
		close -> %% when client or server exit,use it,gen a tcp_closed at another point
			gen_tcp:close(Socket)
	end.

你可能感兴趣的:(socket,erlang)