Erlang中的half-sync/half-async和Leader/Followers 模式

http://www.iteye.com/article/60414
里面,谈到了半同步/半异步和领导者/追随者模式,在Erlang里面可以很简单得实现它

下面看看 half-sync/half-async 的例子
[code]start() ->
case gen_tcp:listen(80, [binary,
{nodelay,true},
{packet, 0},
{reuseaddr, true},
{active, false}]) of
{ok, Listen} ->
io:format("Listning port 80 @ ~p~n", [self()]),
accept_loop(Listen);
Error -> io:format("Error occur: ~p~n", [Error])
end.

accept_loop(Listen) ->
case gen_tcp:accept(Listen) of
{ok, Socket} ->
io:format("Socket ~p connected~n", [Socket]),
spawn(?MODULE, handler, [Socket]),
accept_loop(Listen);
Other -> exit(oops)
end.

handler(Socket) ->
io:format("Waiting incoming message @ ~p~n", [self()]),
inet:setopts(Socket, [{nodelay,true}, {active, false}]),
case gen_tcp:recv(Socket, 0) of
{ok, Packet} ->
io:format("Receive msg ~p~n", [binary_to_list(Packet)]),
gen_tcp:send(Socket, Packet),
gen_tcp:close(Socket),
handler(Socket);
{error, Reason} ->
io:format("Socket ~p error ~p~n", [Socket, Reason])
end.[/code]

在许多“网络编程”的教程里面,都会给出类似这样的例子。首先当前线程先监听一个端口,然后accept外来Socket连接,并将Socket传递到新的线程中处理。在C、Java这样的语言中,创建一个线程的开销是很大的,一般来说,会使用线程池来处理短连接,一些Web Server就是基于这样的模式。然而在Erlang里面,创建一个Proces的开销极少,进程间切换完全在用户态实现,这样减少了用户态和核心态间切换的开销,使得这种模式成为了可能。


接下来是Leader/Followers模式

[code]start2() ->
case gen_tcp:listen(81, [binary,
{nodelay,true},
{packet, 0},
{reuseaddr, true},
{active, false}]) of
{ok, Listen} ->
handler2(Listen);
Error -> io:format("Error occur: ~p~n", [Error])
end.

handler2(Listen) ->
io:format("Listning port 81 @ ~p~n", [self()]),
case gen_tcp:accept(Listen) of
{ok, Socket} ->
io:format("Socket ~p connected~n", [Socket]),
inet:setopts(Socket, [{nodelay,true}, {active, true}]),
spawn(?MODULE, handler2, [Listen]),
io:format("Waiting incoming message @ ~p~n", [self()]),
receive
{tcp, Socket, Bin} ->
io:format("Receive msg ~p~n", [binary_to_list(Bin)]),
gen_tcp:send(Socket, Bin),
gen_tcp:close(Socket);
{tcp_closed, Socket} ->
io:format("Socket ~p closed ~n", [Socket]);
Any ->
io:format("~p~n", [Any])
end;
Other ->
io:format("~p~n", [Other]),
exit(oops)
end.[/code]


当一个Socket连接建立后,就会将监听gen_tcp:accept/1的调用权转移到新的Process当中进行处理。

在这里,Leader Process 设置了这样一个参数
inet:setopts(Socket, [{nodelay,true}, {active, true}]),

在gen_tcp模块的文档中,有一段如下的说明

[quote]Packets can be sent to the returned socket Socket using send/2. Packets sent from the peer are delivered as messages:
{tcp, Socket, Data}

unless {active, false} was specified in the option list for the listen socket, in which case packets are retrieved by calling recv/2.[/quote]

当在gen_tcp:listen/2中使用了{active, true}参数,那么当接收到数据的时候,就会主动发送消息到调用gen_tcp:accept/1的Process中,否则需要使用 gen_tcp:recv 来阻塞获取。通过这样的方式,就可以灵活实现同步/异步接收Socket数据。

Erlang网络编程还有其他有趣的地方,接下来的笔记我会写写这方面的内容。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值