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的源码。

你可能感兴趣的:(net)