net

gen_tcp模块:

主要的选项:
option() = {active, true | false }
| {buffer, integer() >= 0}
| {delay_send, boolean()}
| {deliver, port | term}
| {exit_on_close, boolean()}
| {header, integer() >= 0}
| {keepalive, boolean()}
| {mode, list | binary}
| list
| binary
| {nodelay, boolean()}
| {packet,
0 |
1 |
2 |
4 |
| {packet_size, integer() >= 0}
| {raw,
Protocol :: integer() >= 0,
OptionNum :: integer() >= 0,
ValueBin :: binary()}
| {recbuf, integer() >= 0}
| {reuseaddr, boolean()}
| {send_timeout, integer() >= 0 | infinity}
| {send_timeout_close, boolean()}
| {sndbuf, integer() >= 0}

连接:
connect(Address, Port, Options) -> {ok, Socket} | {error, Reason}
connect(Address, Port, Options, Timeout) -> {ok, Socket} | {error, Reason}
{ok, Sock} = gen_tcp:connect("localhost", 5678, [binary, {packet, 0}]),

监听端口:
listen(Port, Options) -> {ok, ListenSocket} | {error, Reason}
{ok, LSock} = gen_tcp:listen(5678, [binary, {packet, 0}, {active, false}]),

接受连接(阻塞):
accept(ListenSocket) -> {ok, Socket} | {error, Reason}
accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason}


发送:
send(Socket, Packet) -> ok | {error, Reason}

主动接收 (阻塞, 前提 {active, true}):
recv(Socket, Length) -> {ok, Packet} | {error, Reason}
recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason}

The Length argument is only meaningful when the socket is in raw mode and denotes the number of bytes to read. If Length = 0, all available bytes are returned. .

当{active,false}时, 数据以 {tcp, Socket, Data} 带外消息传递给socket的控制进程.

更改socket的控制进程:
controlling_process(Socket, Pid) -> ok | {error, Reason}

调用gen_tcp:accept或gen_tcp:connect的进程 是socket的原始控制进程,该套接字所收到的任何消息都会转发给这个控制进程,如果控制进程消亡,那么该套接字也会自行关闭。

关闭socket:
close(Socket) -> ok
shutdown(Socket, How) -> ok | {error, Reason}
How = read | write | read_write
Immediately close a socket in one or two directions.
the {exit_on_close, false} option is useful.


处理socket的选项 inet模块
inet:setopts(Socket, Options) -> ok | {error, posix()}

prim_inet:async_accept和prim_inet:async_recv是非阻塞的实现方案,可参看Rabbitmq的源码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值