gen_tcp(3)
๐ gen_tcp(3) โ Erlang Module Definition ๐
okay bestie, welcome to the gen_tcp page โ the Erlang module definition for talking over TCP/IP sockets, and honestly? iconic. It's giving "networking but make it Erlang", and we're gonna go through it together, no cap. ๐
โจ NAME โจ
gen_tcp โ Interface to TCP/IP sockets.
๐ธ DESCRIPTION ๐ธ
This module provides functions for communicating over TCP/IP protocol sockets. That's the whole vibe: you get sockets, you send bytes, you receive bytes, you close stuff, periodt.
The following code fragment is a simple example of a client connecting to a server at port 5678, transferring a binary, and closing the connection:
client() ->
SomeHostInNet = "localhost", % to make it runnable on one machine
{ok, Sock} = gen_tcp:connect(SomeHostInNet, 5678,
[binary, {packet, 0}]),
ok = gen_tcp:send(Sock, "Some Data"),
ok = gen_tcp:close(Sock).
At the other end, a server is listening on port 5678, accepts the connection, and receives the binary:
server() ->
{ok, LSock} = gen_tcp:listen(5678, [binary, {packet, 0},
{active, false}]),
{ok, Sock} = gen_tcp:accept(LSock),
{ok, Bin} = do_recv(Sock, []),
ok = gen_tcp:close(Sock),
ok = gen_tcp:close(LSock),
Bin.
do_recv(Sock, Bs) ->
case gen_tcp:recv(Sock, 0) of
{ok, B} ->
do_recv(Sock, [Bs, B]);
{error, closed} ->
{ok, list_to_binary(Bs)}
end.
For more examples, see section Examples.
NOTE: Functions that create sockets can take an optional option;{inet_backend, Backend}that, if specified, has to be the first option. This selects the implementation backend towards the platform's socket API. This is a temporary option that will be ignored in a future release. The default isBackend = inetthat selects the traditionalinet_drv.cdriver. The other choice isBackend = socketthat selects the newsocketmodule and its NIF implementation. The system default can be changed when the node is started with the applicationkernel's configuration variableinet_backend. Forgen_tcpwithinet_backend = socketwe have tried to be as "compatible" as possible which has sometimes been impossible. Here is a list of cases when the behaviour of inet-backendinet(default) andsocketare different:
- Non-blocking send โ If a user calling
gen_tcp:send/2withinet_backend = inet, tries to send more data than there is room for in the OS buffers, the "rest data" is buffered by theinetdriver (and later sent in the background). The effect for the user is that the call is non-blocking. This is not the effect wheninet_backend = socket, since there is no buffering. Instead the user hangs either until all data has been sent or thesend_timeouttimeout has been reached. shutdown/2may hide errors โ The call does not involve the receive process state, and is done right on the underlying socket. On for example Linux, it is a known misbehaviour that it skips some checks so doingshutdownon a listen socket returnsokwhile the logical result should have been{error, enotconn}. Theinet_drv.cdriver did an extra check and simulated the correct error, but withBackend = socketit would introduce overhead to involve the receive process.- The option
nodelayis a TCP specific option that is not compatible withdomain = local. When usinginet_backend = socket, trying to create a socket (vialistenorconnect) withdomain = local(for example with option{ifaddr, {local,"/tmp/test"}}) will fail with{error, enotsup}. This does not actually work forinet_backend = ineteither, but in that case the error is simply ignored, which is a bad idea. We have chosen to not ignore this error forinet_backend = socket. - Async shutdown write โ Calling
gen_tcp:shutdown(Socket, write | read_write)on a socket created withinet_backend = socketwill take immediate effect, unlike for a socket created withinet_backend = inet. See async shutdown write for more info. - Windows require sockets (
domain = inet | inet6) to be bound. Currently all sockets created on Windows withinet_backend = socketwill be bound. If the user does not provide an address,gen_tcpwill try to 'figure out' an address itself.
๐ Examples ๐
The following example illustrates use of option {active,once} and multiple accepts by implementing a server as a number of worker processes doing accept on a single listening socket. Function start/2 takes the number of worker processes and the port number on which to listen for incoming connections. If LPort is specified as 0, an ephemeral port number is used, which is why the start function returns the actual port number allocated:
start(Num,LPort) ->
case gen_tcp:listen(LPort,[{active, false},{packet,2}]) of
{ok, ListenSock} ->
start_servers(Num,ListenSock),
{ok, Port} = inet:port(ListenSock),
Port;
{error,Reason} ->
{error,Reason}
end.
start_servers(0,_) ->
ok;
start_servers(Num,LS) ->
spawn(?MODULE,server,[LS]),
start_servers(Num-1,LS).
server(LS) ->
case gen_tcp:accept(LS) of
{ok,S} ->
loop(S),
server(LS);
Other ->
io:format("accept returned ~w - goodbye!~n",[Other]),
ok
end.
loop(S) ->
inet:setopts(S,[{active,once}]),
receive
{tcp,S,Data} ->
Answer = process(Data), % Not implemented in this example
gen_tcp:send(S,Answer),
loop(S);
{tcp_closed,S} ->
io:format("Socket ~w closed [~w]~n",[S,self()]),
ok
end.
Example of a simple client:
client(PortNo,Message) ->
{ok,Sock} = gen_tcp:connect("localhost",PortNo,[{active,false},
{packet,2}]),
gen_tcp:send(Sock,Message),
A = gen_tcp:recv(Sock,0),
gen_tcp:close(Sock),
A.
The send call does not accept a time-out option because time-outs on send is handled through socket option send_timeout. The behavior of a send operation with no receiver is mainly defined by the underlying TCP stack and the network infrastructure. To write code that handles a hanging receiver that can eventually cause the sender to hang on a send do like the following.
Consider a process that receives data from a client process to be forwarded to a server on the network. The process is connected to the server through TCP/IP and does not get any acknowledge for each message it sends, but has to rely on the send time-out option to detect that the other end is unresponsive. Option send_timeout can be used when connecting:
{ok,Sock} = gen_tcp:connect(HostAddress, Port,
[{active,false},
{send_timeout, 5000},
{packet,2}]),
loop(Sock), % See below
In the loop where requests are handled, send time-outs can now be detected:
loop(Sock) ->
receive
{Client, send_data, Binary} ->
case gen_tcp:send(Sock,[Binary]) of
{error, timeout} ->
io:format("Send timeout, closing!~n",
[]),
handle_send_timeout(), % Not implemented here
Client ! {self(),{error_sending, timeout}},
%% Usually, it's a good idea to give up in case of a
%% send timeout, as you never know how much actually
%% reached the server, maybe only a packet header?!
gen_tcp:close(Sock);
{error, OtherSendError} ->
io:format("Some other error on socket (~p), closing",
[OtherSendError]),
Client ! {self(),{error_sending, OtherSendError}},
gen_tcp:close(Sock);
ok ->
Client ! {self(), data_sent},
loop(Sock)
end
end.
Usually it suffices to detect time-outs on receive, as most protocols include some sort of acknowledgment from the server, but if the protocol is strictly one way, option send_timeout comes in handy.
๐ DATA TYPES ๐
okay bestie, before we even touch the functions, we gotta meet the type besties. these are the little shape-shifters that show up all over gen_tcp. no cap, knowing them is the vibe check. ๐
connect_option() ::
{fd, Fd :: non_neg_integer()} |
inet:address_family() |
{ifaddr,
socket:sockaddr_in() |
socket:sockaddr_in6() |
inet:socket_address()} |
{ip, inet:socket_address()} |
{port, inet:port_number()} |
{tcp_module, module()} |
{netns, file:filename_all()} |
{bind_to_device, binary()} |
option().
listen_option() ::
{fd, Fd :: non_neg_integer()} |
inet:address_family() |
{ifaddr,
socket:sockaddr_in() |
socket:sockaddr_in6() |
inet:socket_address()} |
{ip, inet:socket_address()} |
{port, inet:port_number()} |
{backlog, B :: non_neg_integer()} |
{tcp_module, module()} |
{netns, file:filename_all()} |
{bind_to_device, binary()} |
option().
option() ::
{active, true | false | once | -32768..32767} |
{buffer, non_neg_integer()} |
{debug, boolean()} |
{delay_send, boolean()} |
{deliver, port | term} |
{dontroute, boolean()} |
{exit_on_close, boolean()} |
{exclusiveaddruse, boolean()} |
{header, non_neg_integer()} |
{high_msgq_watermark, pos_integer()} |
{high_watermark, non_neg_integer()} |
{keepalive, boolean()} |
{keepcnt, integer()} |
{keepidle, integer()} |
{keepintvl, integer()} |
{linger, {boolean(), non_neg_integer()}} |
{low_msgq_watermark, pos_integer()} |
{low_watermark, non_neg_integer()} |
{mode, list | binary} |
list | binary |
{nodelay, boolean()} |
{packet,
0 | 1 | 2 | 4 | raw | sunrm | asn1 | cdr | fcgi | line |
tpkt | http | httph | http_bin | httph_bin} |
{packet_size, non_neg_integer()} |
{priority, non_neg_integer()} |
{raw,
Protocol :: non_neg_integer(),
OptionNum :: non_neg_integer(),
ValueBin :: binary()} |
{recbuf, non_neg_integer()} |
{reuseaddr, boolean()} |
{reuseport, boolean()} |
{reuseport_lb, boolean()} |
{send_timeout, timeout()} |
{send_timeout_close, boolean()} |
{show_econnreset, boolean()} |
{sndbuf, non_neg_integer()} |
{tos, non_neg_integer()} |
{tclass, non_neg_integer()} |
{ttl, non_neg_integer()} |
{recvtos, boolean()} |
{recvtclass, boolean()} |
{recvttl, boolean()} |
{user_timeout, non_neg_integer()} |
{ipv6_v6only, boolean()}.
option_name() ::
active | buffer | debug | delay_send | deliver | dontroute |
exit_on_close | exclusiveaddruse | header |
high_msgq_watermark | high_watermark | keepalive | keepcnt |
keepidle | keepintvl | linger | low_msgq_watermark |
low_watermark | mode | nodelay | packet | packet_size |
priority |
{raw,
Protocol :: non_neg_integer(),
OptionNum :: non_neg_integer(),
ValueSpec ::
(ValueSize :: non_neg_integer()) | (ValueBin ::
binary())} |
recbuf | reuseaddr | reuseport | reuseport_lb | send_timeout |
send_timeout_close | show_econnreset | sndbuf | tos | tclass |
ttl | recvtos | recvtclass | recvttl | pktoptions |
user_timeout | ipv6_v6only.
pktoptions_value() :: {pktoptions, inet:ancillary_data()}.
Value from socket option pktoptions.
If the platform implements the IPv4 option IP_PKTOPTIONS, or the IPv6 option IPV6_PKTOPTIONS or IPV6_2292PKTOPTIONS for the socket; this value is returned from inet:getopts/2 when called with the option name pktoptions.
NOTE: This option appears to be VERY Linux specific, and its existence in future Linux kernel versions is also worrying since the option is part of RFC 2292 which is since long (2003) obsoleted by RFC 3542 that explicitly removes this possibility to get packet information from a stream socket. For comparison: it has existed in FreeBSD but is now removed, at least since FreeBSD 10. ๐ญ
socket() :: inet:socket().
As returned by accept/1,2 and connect/3,4.
โจ FUNCTIONS โจ
okay bestie, now the main character energy: the functions. these are the moves you'll actually be pulling. ๐
๐ซถ accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason} ๐ซถ
accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason}
when
ListenSocket :: socket(),
Timeout :: timeout(),
Socket :: socket(),
Reason ::
closed | timeout | system_limit | inet:posix().
Accept an incoming connection request on a listen socket.
ListenSocket must be a socket returned from listen/2. Timeout specifies a time-out value in milliseconds. Defaults to infinity.
Returns:
{ok, Socket}if a connection is established{error, closed}ifListenSocketis closed{error, timeout}if no connection is established withinTimeout{error, system_limit}if all available ports in the Erlang emulator are in use- POSIX error value if something else goes wrong, see
inetabout possible values
To send packets (outbound) on the returned Socket, use send/2. Packets sent from the peer (inbound) are delivered as messages to the socket owner; the process that created the socket. Unless {active, false} is specified in the option list when creating the listening socket.
See connect/4 about active mode socket messages and passive mode.
NOTE: Theacceptcall doesn't have to be issued from the socket owner process. Using version5.5.3and higher of the emulator, multiple simultaneousacceptcalls can be issued from different processes, which allows for a pool of acceptor processes handling incoming connections. ๐
๐ close(Socket) -> ok ๐
close(Socket) -> ok when Socket :: socket().
Close a TCP socket.
Note that in most implementations of TCP, doing a close does not guarantee that the data sent is delivered to the recipient. It is guaranteed that the recipient will see all sent data before getting the close, but the sender gets no indication of that. ๐ญ
If the sender needs to know that the recipient has received all data there are two common ways to achieve this:
- Use
gen_tcp:shutdown(Sock, write)to signal that no more data is to be sent and wait for the other side to acknowledge seeing its read side being closed, by closing its write side, which shows as a socket close on this side. - Implement an acknowledgement in the protocol on top of TCP that both connection ends adhere to, indicating that all data has been seen. The socket option
{packet, N}may be useful. โจ
๐ connect(SockAddr, Opts) -> {ok, Socket} | {error, Reason} ๐
connect(SockAddr, Opts) -> {ok, Socket} | {error, Reason}
when
SockAddr ::
socket:sockaddr_in() | socket:sockaddr_in6(),
Opts :: [inet:inet_backend() | connect_option()],
Socket :: socket(),
Reason :: inet:posix().
Equivalent to connect(SockAddr, Opts, infinity).
๐ connect(Address, Port, Opts) -> {ok, Socket} | {error, Reason} / (SockAddr, Opts, Timeout) -> {ok, Socket} | {error, Reason} ๐
connect(Address, Port, Opts) -> {ok, Socket} | {error, Reason}
when
Address :: inet:socket_address() | inet:hostname(),
Port :: inet:port_number(),
Opts :: [inet:inet_backend() | connect_option()],
Socket :: socket(),
Reason :: inet:posix();
(SockAddr, Opts, Timeout) -> {ok, Socket} | {error, Reason}
when
SockAddr ::
socket:sockaddr_in() | socket:sockaddr_in6(),
Opts :: [inet:inet_backend() | connect_option()],
Timeout :: timeout(),
Socket :: socket(),
Reason :: timeout | inet:posix().
Create a socket connected to the specified address.
With arguments Address and Port
Equivalent to connect(Address, Port, Opts, infinity).
With argument SockAddr (since OTP 24.3)
Connects to a remote listen socket specified by SockAddr where socket:sockaddr_in6/0 for example allows specifying the scope_id for link local IPv6 addresses.
IPv4 addresses on the same map/0 format is also allowed.
Equivalent to connect/4, besides the format of the destination address.
๐ซ connect(Address, Port, Opts, Timeout) -> {ok, Socket} | {error, Reason} ๐ซ
connect(Address, Port, Opts, Timeout) ->
{ok, Socket} | {error, Reason}
when
Address :: inet:socket_address() | inet:hostname(),
Port :: inet:port_number(),
Opts :: [inet:inet_backend() | connect_option()],
Timeout :: timeout(),
Socket :: socket(),
Reason :: timeout | inet:posix().
Create a socket connected to the specified address.
Creates a socket and connects it to a server on TCP port Port on the host with IP address Address, that may also be a hostname.
Opts (connect options)
{ip, Address}โ If the local host has many IP addresses, this option specifies which one to use.{ifaddr, Address}โ Same as{ip, Address}.
However, if Address instead is a socket:sockaddr_in/0 or socket:sockaddr_in6/0 this takes precedence over any value previously set with the ip and port options. If these options (ip or/and port) however comes after this option, they may be used to update the corresponding fields of this option (for ip, the addr field, and for port, the port field).
{fd, integer() >= 0}โ If a socket has somehow been connected without usinggen_tcp, use this option to pass the file descriptor for it. If{ip, Address}and/or{port, port_number()}is combined with this option, thefdis bound to the specified interface and port before connecting. If these options are not specified, it is assumed that thefdis already bound appropriately.inetโ sets up the socket for IPv4. ๐inet6โ sets up the socket for IPv6. ๐localโ sets up a Unix Domain Socket. Check outinet:local_address/0๐ฆ{port, Port}โ tells you exactly which local port number to use. ๐ฎ{tcp_module, module()}โ overrides which callback module is used. Defaults toinet_tcpfor IPv4 andinet6_tcpfor IPv6. ๐ง{protocol, tcp|mptcp}โ withmptcpit creates the socket with protocolIPPROTO_MPTCP, if that is defined on your system. Other than that, the socket is regarded as a tcp socket. IfIPPROTO_MPTCPis not defined,{error, eprotonosupport}is returned.tcpis the default value. ๐ฅoption/0โ seeinet:setopts/2. ๐
๐ Socket Data ๐
Packets can be sent to the peer (outbound) with send(Socket, Packet). Packets sent from the peer (inbound) are delivered as messages to the socket owner โ that's the process that created the socket, unless {active, false} is specified in the Options list. ๐
๐ Active mode socket messages ๐
{tcp, Socket, Data}โ inbound data from the socket. ๐ฅ{tcp_passive, Socket}โ the socket was in{active, N}mode (seeinet:setopts/2for details) and its message counter reached 0, indicating that the socket has transitioned to passive ({active, false}) mode. ๐ด{tcp_closed, Socket}โ the socket was closed. ๐ช{tcp_error, Socket, Reason}โ a socket error occurred. ๐
๐๏ธ Passive mode ๐๏ธ
If {active, false} is specified in the option list for the socket, packets and errors are retrieved by calling recv/2,3 (send/2 may also return errors). ๐ซถ
โณ Timeout โณ
The optional Timeout parameter specifies a connect time-out in milliseconds. Defaults to infinity. โพ๏ธ
NOTE: Keep in mind that if the underlying OSconnect()call returns a timeout,gen_tcp:connectwill also return a timeout (i.e.{error, etimedout}), even if a largerTimeoutwas specified (for exampleinfinity). ๐ญ
NOTE: The default values for options specified to connect can be affected by the Kernel configuration parameterinet_default_connect_options. For details, seeinet. ๐
๐ controlling_process(Socket, Pid) -> ok | {error, Reason} ๐
controlling_process(Socket, Pid) -> ok | {error, Reason}
when
Socket :: socket(),
Pid :: pid(),
Reason ::
closed | not_owner | badarg |
inet:posix().
Change the controlling process (owner) of a socket. ๐
Assigns a new controlling process Pid to Socket. The controlling process is the process that the socket sends messages to. If this function is called from any other process than the current controlling process, {error, not_owner} is returned. ๐ซ
If the process identified by Pid is not an existing local pid/0, {error, badarg} is returned. {error, badarg} may also be returned in some cases when Socket is closed during the execution of this function. ๐ต
If the socket is in active mode, this function will transfer any messages from the socket in the mailbox of the caller to the new controlling process. ๐ฌ
If any other process is interacting with the socket during the transfer, it may not work correctly and messages may remain in the caller's mailbox. For instance, changing the socket's active mode during the transfer could cause this. ๐
๐ง listen(Port, Options) -> {ok, ListenSocket} | {error, Reason} ๐ง
listen(Port, Options) -> {ok, ListenSocket} | {error, Reason}
when
Port :: inet:port_number(),
Options :: [inet:inet_backend() | listen_option()],
ListenSocket :: socket(),
Reason :: system_limit | inet:posix().
Create a listen socket. ๐ ๏ธ
Creates a socket and sets it to listen on port Port on the local host. ๐
If Port == 0, the underlying OS assigns an available (ephemeral) port number, use inet:port/1 to retrieve it. ๐ฒ
The following options are available: ๐
listโ received Packets are delivered as lists of bytes,[byte/0]. ๐binaryโ received Packets are delivered asbinary/0s. ๐ข{backlog, B}โ whereB :: non_neg_integer/0. The backlog value defines the maximum length that the queue of pending connections can grow to. Defaults to5. ๐inet6โ sets up the socket for IPv6. ๐inetโ sets up the socket for IPv4. ๐{fd, Fd}โ if a socket has somehow been created without usinggen_tcp, use this option to pass the file descriptor for it. ๐๏ธ{ip, Address}โ if the host has many IP addresses, this option specifies which one to listen on. ๐{port, Port}โ specifies which local port number to use. ๐ฎ{ifaddr, Address}โ same as{ip, Address}. However, if this instead is asocket:sockaddr_in/0orsocket:sockaddr_in6/0this takes precedence over any value previously set with theipandportoptions. If these options (ipor/andport) however comes after this option, they may be used to update their corresponding fields of this option (forip, theaddrfield, and forport, theportfield). ๐งฌ{tcp_module, module()}โ overrides which callback module is used. Defaults toinet_tcpfor IPv4 andinet6_tcpfor IPv6. ๐ง{protocol, tcp|mptcp}โ withmptcpcreates the socket with protocolIPPROTO_MPTCP, if that is defined on the system. Other than that the socket is regarded as atcpsocket. IfIPPROTO_MPTCPis not defined,{error, eprotonosupport}is returned.tcpis the default value. ๐ฅoption/0โ seeinet:setopts/2. ๐
The returned socket ListenSocket should be used when calling accept/1,2 to accept an incoming connection request. ๐ค
NOTE: The default values for options specified to listen can be affected by the Kernel configuration parameterinet_default_listen_options. For details, seeinet. ๐
๐ฅ recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason} ๐ฅ
recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason}
when
Socket :: socket(),
Length :: non_neg_integer(),
Timeout :: timeout(),
Packet :: string() | binary() | HttpPacket,
Reason :: closed | timeout | inet:posix(),
HttpPacket :: term().
Receive a packet, from a socket in passive mode. ๐จ
A closed socket is indicated by the return value {error, closed}. If the socket is not in passive mode, the return value is {error, einval}. ๐ซ
Argument Length is only meaningful when the socket is in raw mode and denotes the number of bytes to read. If Length is 0, all available bytes are returned. If Length > 0, exactly Length bytes are returned, or an error; except if the socket is closed from the other side, then the last read before the one returning {error, closed} may return less than Length bytes of data. ๐
The optional Timeout parameter specifies a time-out in milliseconds. Defaults to infinity. โณ
Any process can receive data from a passive socket, even if that process is not the controlling process of the socket. However, only one process can call this function on a socket at any given time. Using simultaneous calls to recv is not recommended as the behavior depends on the socket implementation, and could return errors such as {error, ealready}. โ ๏ธ
๐ค send(Socket, Packet) -> ok | {error, Reason} ๐ค
send(Socket, Packet) -> ok | {error, Reason}
when
Socket :: socket(),
Packet :: iodata(),
Reason :: closed | {timeout, RestData} | inet:posix(),
RestData :: binary() | erlang:iovec().
Send a packet on a socket. ๐
There is no send/2 call with a time-out option; use socket option send_timeout if time-outs are desired. See section Examples. โฑ๏ธ
The return value {error, {timeout, RestData}} can only be returned when inet_backend = socket. ๐ซ
Note Non-blocking send. If the user tries to send more data than there is room for in the OS send buffers, the 'rest data' is stored in (inet driver) internal buffers and later sent in the background. The function immediately returnsok(not informing the caller that some data isn't sent yet). Any issue while sending the 'rest data' may be returned later. When usinginet_backend = socket, the behaviour is different. There is no buffering, instead the caller will "hang" until all of the data has been sent or the send timeout (as specified by thesend_timeoutoption) expires (the function can "hang" even when using the inet backend if the internal buffers are full). If this happens when usingpacket =/= raw, a partial packet has been written. A new packet therefore mustn't be written at this point, as there is no way for the peer to distinguish this from data in the current packet. Instead, set thepacketoption toraw, send the rest data (as raw data) and then setpacketback to the correct type. ๐ฑ
๐ shutdown(Socket, How) -> ok | {error, Reason} ๐
shutdown(Socket, How) -> ok | {error, Reason}
when
Socket :: socket(),
How :: read | write | read_write,
Reason :: inet:posix().
Close the socket in one or both directions. ๐ช
How == write means closing the socket for writing, reading from it is still possible. โ๏ธ
If How == read or there is no outgoing data buffered in the Socket port, the shutdown is performed immediately and any error encountered is returned in Reason. โก
If there is data buffered in the socket port, shutdown isn't performed on the socket until that buffered data has been written to the OS protocol stack. If any errors are encountered, the socket is closed and {error, closed} is returned by the next recv/2 or send/2 call. ๐
ok one more lil closing-adjacent thing and then we're done bestie, promise ๐ซถ
{exit_on_close, false}โ this one is your bestie when the other side does a shutdown of its write side ๐ . With it set, the socket stays open for writing even afterreceivehas already told you the socket was closed. Like, the read side said bye ๐ but your write side is still very much in the building. Iconic, honestly.
NOTE: Async shutdown write (How :: write | read_write) โ ๏ธโจ โ okay so listen closely, this is the spicy part. If the shutdown attempt happens while the inet driver is still sending buffered data in the background, the shutdown gets postponed until all that buffered data has been sent. And here's the gag: the function immediately returnsok, and the caller is not informed that the shutdown was postponed. Not a single text, not a single notification. ๐ Silence.
๐ธ But wait โ when you're usinginet_backend = socket, the behaviour is different. A shutdown withHow :: write | read_writewill always be performed immediately. No postponing, no waiting around for the buffer, it just goes. Periodt.
and that's the whole page, bestie!! ๐ you just read gen_tcp(3) start to finish and you ate, no crumbs left ๐
this one's brought to you by Ericsson AB (source) outta the kernel 11.0.3 era (version), and yes the footer date is living right there at the bottom of the real page โ go peek at it if you need timestamps ๐
โจ
go forth and socket responsibly ๐๐ธ๐ฆ๐
๐ฆ where this page comes from
- ubuntu stonking: erlang-doc 1:29.0.6+dfsg-1 ยท Apache-2.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms