关于Erlang Socket的三种消息接收模式

本文介绍了Erlang中socket的三种消息接收模式:active(主动)、passive(被动)和activeonce(混合)。重点讲解了activeonce模式的工作原理及优势,并提及Erlang官方推荐使用该模式。

转载请注明,来自:http://blog.youkuaiyun.com/skyman_2001

erlang的socket有3种消息接收模式:active、passive和active once,可以在gen_tcp:connect/3或gen_tcp:listen/2里设置{active, true | false |once}来实现,也可以用inet:setopts/2来动态设置。这3种模式的区别是:

1. active(主动消息接收):非阻塞。当数据到达时系统会向控制进程发送{tcp, Socket, Data}消息。控制进程无法控制消息流;

2. passive(被动消息接收):阻塞。控制进程必须主动调用recv()来接收消息。可以控制消息流;

3. active once(混合消息接收):半阻塞。这种模式是主动的但仅针对一个消息,在控制进程收到一个消息后,必须显式调用inet:setopts(Socket, [{active, once}])来重新

激活以接收下一个消息。可以进行流量控制。这种模式相对于被动模式来说,有个优点是可以同时等待多个socket的数据。


Erlang官方推荐使用active once模式:

Active, once is the recommended way to implement a server in both UDP and
TCP.

The use of active once is superior to the other alternatives from a
programmatical standpoint, it is clean and robust. I don't recommend the
use of active true or active false just for performance reasons, because it
will cause other problems instead.

We are currently working with improvements regarding active once for TCP
since it obviously seems to be slower than necessary. Most probably it is
the same with UDP and we will look into that as well.

We don't think there need any significant performance difference between
active once and the other alternatives and hope to have a solution
confirming that soon (meaning r15b02 or 03)

Regards Kenneth Erlang/OTP, Ericsson

详见:http://erlang.org/pipermail/erlang-questions/2012-April/065991.html


R15B02对active once进行了优化,降低延迟,最大吞吐量提高4~6倍。详见:https://github.com/erlang/otp/commit/689ba6e5657867eb3efbcb9a2dbec4aa98ddac5d

在Delphi中,套接字(Socket)编程用到的基本类是TServerSocket与TClientSocket。这两个类全部位于ScktComp单元中。其类型定义如下:    type TServerSocket = class (ScktComp.TCustomServerSocket); TClientSocket = class (ScktComp.TCustomSocket)。      在编写程序时,首先要对TServerSocket(在服务器端)与TClientSocket(在客户端)进行实例化。对于TServerSocket的对象,主要设置其服务类型(ServerType)与端口(Port)的属性,然后编写“OnClientRead”事件处理程序的代码,处理来自客户机的请求。如要启动服务器,设置TServerSocket对象的Active属性为真(即Active := True),如要停止服务器,则设置TServerSocket对象的Active属性为假(即Active := False)。      对于TClientSocket的对象,主要设置对方服务器的服务类型(ServerType)、端口(Port)以及IP地址(Address)的属性,之后编写“OnConnect与OnRead”事件处理程序的代码“OnConnect”事件处理程序用来检查与服务器连接成功与否(必须在这里进行检查才有效),“OnRead”事件处理程序用来读取服务器发来的信息。如要连接服务器,设置TClientSocket对象的Active属性为真(即Active := True;注意:检查连接是否成功,必须在“OnConnect”事件处理程序中进行),如要断开与服务器的连接,则设置TClientSocket对象的Active属性为假(即Active := False)。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值