.TH gen_tcp 3erl "kernel 9.2.3" "Ericsson AB" "Erlang Module Definition" .SH NAME gen_tcp \- Interface to TCP/IP sockets. .SH DESCRIPTION .LP This module provides functions for communicating with sockets using the TCP/IP protocol\&. .LP 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: .LP .nf 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). .fi .LP At the other end, a server is listening on port 5678, accepts the connection, and receives the binary: .LP .nf 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. .fi .LP For more examples, see section Examples\&. .LP .RS -4 .B Note: .RE Functions that create sockets can take an optional option; \fI{inet_backend, Backend}\fR\& that, if specified, has to be the first option\&. This selects the implementation backend towards the platform\&'s socket API\&. .LP This is a \fItemporary\fR\& option that will be ignored in a future release\&. .LP The default is \fIBackend = inet\fR\& that selects the traditional \fIinet_drv\&.c\fR\& driver\&. The other choice is \fIBackend = socket\fR\& that selects the new \fIsocket\fR\& module and its NIF implementation\&. .LP The system default can be changed when the node is started with the application \fIkernel\fR\&\&'s configuration variable \fIinet_backend\fR\&\&. .LP For \fIgen_tcp\fR\& with \fIinet_backend = socket\fR\& we have tried to be as "compatible" as possible which has sometimes been impossible\&. Here is a list of cases when the behaviour of inet-backend \fIinet\fR\& (default) and \fIsocket\fR\& are different: .RS 2 .TP 2 * Non-blocking send .RS 2 .LP If a user calling \fIgen_tcp:send/2\fR\& with \fIinet_backend = inet\fR\&, tries to send more data than there is room for in the OS buffers, the "rest data" is buffered by the inet driver (and later sent in the background)\&. The effect for the user is that the call is non-blocking\&. .RE .RS 2 .LP This is \fInot\fR\& the effect when \fIinet_backend = socket\fR\&, since there is no buffering\&. Instead the user hangs either until all data has been sent or the \fIsend_timeout\fR\& timeout has been reached\&. .RE .LP .TP 2 * Remote close detected by background send\&. .RS 2 .LP An background send will detect a \&'remote close\&' and (the inet driver will) mark the socket as \&'closed\&'\&. No other action is taken\&. If the socket has \fIactive\fR\& set to \fIfalse\fR\& (passive) at this point and no one is reading, this will not be noticed\&. But as soon as the socket is "activated" (\fIactive\fR\& set to not \fIfalse\fR\&, send/2 is called or recv/2,3 is called), an error message will be sent to the caller or (socket) owner: \fI{tcp_error, Socket, econnreset}\fR\&\&. Any data in the OS receive buffers will be lost! .RE .RS 2 .LP This behaviour is \fInot\fR\& replicated by the socket implementation\&. A send operation will detect a remote close and immediately return this to the caller, but do nothing else\&. A reader will therefore be able to extract any data from the OS buffers\&. If the socket is set to \fIactive\fR\& not \fIfalse\fR\&, the data will be received as expected (\fI{tcp, \&.\&.\&.}\fR\& and then a closed message (\fI{tcp_closed, \&.\&.\&.}\fR\& will be received (not an error)\&. .RE .LP .TP 2 * The option show_econnreset basically do \fInot\fR\& work as described when used with \fIinet_backend = socket\fR\&\&. The "issue" is that a remote close (as described above) \fIdo\fR\& allow a reader to extract what is in the read buffers before a close is "delivered"\&. .LP .TP 2 * The option nodelay is a TCP specific option that is \fInot\fR\& compatible with \fIdomain = local\fR\&\&. .RS 2 .LP When using \fIinet_backend = socket\fR\&, trying to create a socket (via listen or connect) with \fIdomain = local\fR\& (for example with option {ifaddr, {local,"/tmp/test"}}) \fIwill fail\fR\& with \fI{error, enotsup}\fR\&\&. .RE .RS 2 .LP This does not actually work for \fIinet_backend = inet\fR\& either, but in that case the error is simply \fIignored\fR\&, which is a \fIbad\fR\& idea\&. We have chosen to \fInot\fR\& ignore this error for \fIinet_backend = socket\fR\&\&. .RE .LP .TP 2 * Async shutdown write .RS 2 .LP Calling gen_tcp:shutdown(Socket, write | read_write) on a socket created with \fIinet_backend = socket\fR\& will take \fIimmediate\fR\& effect, unlike for a socket created with \fIinet_backend = inet\fR\&\&. .RE .RS 2 .LP See async shutdown write for more info\&. .RE .LP .TP 2 * Windows require sockets (domain = \fIinet | inet6\fR\&) to be bound\&. .RS 2 .LP \fICurrently\fR\& all sockets created on Windows with \fIinet_backend = socket\fR\& will be bound\&. If the user does not provide an address, gen_tcp will try to \&'figure out\&' an address itself\&. .RE .LP .RE .SH DATA TYPES .nf \fBoption()\fR\& = .br {active, true | false | once | -32768\&.\&.32767} | .br {buffer, integer() >= 0} | .br {debug, boolean()} | .br {delay_send, boolean()} | .br {deliver, port | term} | .br {dontroute, boolean()} | .br {exit_on_close, boolean()} | .br {exclusiveaddruse, boolean()} | .br {header, integer() >= 0} | .br {high_msgq_watermark, integer() >= 1} | .br {high_watermark, integer() >= 0} | .br {keepalive, boolean()} | .br {linger, {boolean(), integer() >= 0}} | .br {low_msgq_watermark, integer() >= 1} | .br {low_watermark, integer() >= 0} | .br {mode, list | binary} | .br list | binary | .br {nodelay, boolean()} | .br {packet, .br 0 | 1 | 2 | 4 | raw | sunrm | asn1 | cdr | fcgi | line | .br tpkt | http | httph | http_bin | httph_bin} | .br {packet_size, integer() >= 0} | .br {priority, integer() >= 0} | .br {raw, .br Protocol :: integer() >= 0, .br OptionNum :: integer() >= 0, .br ValueBin :: binary()} | .br {recbuf, integer() >= 0} | .br {reuseaddr, boolean()} | .br {reuseport, boolean()} | .br {reuseport_lb, boolean()} | .br {send_timeout, integer() >= 0 | infinity} | .br {send_timeout_close, boolean()} | .br {show_econnreset, boolean()} | .br {sndbuf, integer() >= 0} | .br {tos, integer() >= 0} | .br {tclass, integer() >= 0} | .br {ttl, integer() >= 0} | .br {recvtos, boolean()} | .br {recvtclass, boolean()} | .br {recvttl, boolean()} | .br {ipv6_v6only, boolean()} .br .fi .nf \fBpktoptions_value()\fR\& = {pktoptions, inet:ancillary_data()} .br .fi .RS .LP If the platform implements the IPv4 option \fIIP_PKTOPTIONS\fR\&, or the IPv6 option \fIIPV6_PKTOPTIONS\fR\& or \fIIPV6_2292PKTOPTIONS\fR\& for the socket this value is returned from \fIinet:getopts/2\fR\& when called with the option name \fIpktoptions\fR\&\&. .LP .RS -4 .B Note: .RE 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 \fIexplicitly\fR\& 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\&. .RE .nf \fBoption_name()\fR\& = .br active | buffer | debug | delay_send | deliver | dontroute | .br exit_on_close | exclusiveaddruse | header | .br high_msgq_watermark | high_watermark | keepalive | linger | .br low_msgq_watermark | low_watermark | mode | nodelay | packet | .br packet_size | priority | .br {raw, .br Protocol :: integer() >= 0, .br OptionNum :: integer() >= 0, .br ValueSpec :: .br (ValueSize :: integer() >= 0) | (ValueBin :: binary())} | .br recbuf | reuseaddr | reuseport | reuseport_lb | send_timeout | .br send_timeout_close | show_econnreset | sndbuf | tos | tclass | .br ttl | recvtos | recvtclass | recvttl | pktoptions | .br ipv6_v6only .br .fi .nf \fBconnect_option()\fR\& = .br {fd, Fd :: integer() >= 0} | .br inet:address_family() | .br {ifaddr, .br socket:sockaddr_in() | .br socket:sockaddr_in6() | .br inet:socket_address()} | .br {ip, inet:socket_address()} | .br {port, inet:port_number()} | .br {tcp_module, module()} | .br {netns, file:filename_all()} | .br {bind_to_device, binary()} | .br option() .br .fi .nf \fBlisten_option()\fR\& = .br {fd, Fd :: integer() >= 0} | .br inet:address_family() | .br {ifaddr, .br socket:sockaddr_in() | .br socket:sockaddr_in6() | .br inet:socket_address()} | .br {ip, inet:socket_address()} | .br {port, inet:port_number()} | .br {backlog, B :: integer() >= 0} | .br {tcp_module, module()} | .br {netns, file:filename_all()} | .br {bind_to_device, binary()} | .br option() .br .fi .nf .B socket() .br .fi .RS .LP As returned by \fIaccept/1,2\fR\& and \fIconnect/3,4\fR\&\&. .RE .SH EXPORTS .LP .nf .B accept(ListenSocket) -> {ok, Socket} | {error, Reason} .br .fi .br .nf .B accept(ListenSocket, Timeout) -> {ok, Socket} | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 ListenSocket = socket() .br .RS 2 Returned by \fIlisten/2\fR\&\&. .RE Timeout = timeout() .br Socket = socket() .br Reason = closed | timeout | system_limit | inet:posix() .br .RE .RE .RS .LP Accepts an incoming connection request on a listening socket\&. \fISocket\fR\& must be a socket returned from \fIlisten/2\fR\&\&. \fITimeout\fR\& specifies a time-out value in milliseconds\&. Defaults to \fIinfinity\fR\&\&. .LP Returns: .RS 2 .TP 2 * \fI{ok, Socket}\fR\& if a connection is established .LP .TP 2 * \fI{error, closed}\fR\& if \fIListenSocket\fR\& is closed .LP .TP 2 * \fI{error, timeout}\fR\& if no connection is established within the specified time .LP .TP 2 * \fI{error, system_limit}\fR\& if all available ports in the Erlang emulator are in use .LP .TP 2 * A POSIX error value if something else goes wrong, see \fIinet(3erl)\fR\& for possible error values .LP .RE .LP Packets can be sent to the returned socket \fISocket\fR\& using \fIsend/2\fR\&\&. Packets sent from the peer are delivered as messages (unless \fI{active, false}\fR\& is specified in the option list for the listening socket, in which case packets are retrieved by calling \fIrecv/2\fR\&): .LP .nf {tcp, Socket, Data} .fi .LP .RS -4 .B Note: .RE The \fIaccept\fR\& call does \fInot\fR\& have to be issued from the socket owner process\&. Using version 5\&.5\&.3 and higher of the emulator, multiple simultaneous accept calls can be issued from different processes, which allows for a pool of acceptor processes handling incoming connections\&. .RE .LP .nf .B close(Socket) -> ok .br .fi .br .RS .LP Types: .RS 3 Socket = socket() .br .RE .RE .RS .LP Closes a TCP socket\&. .LP Note that in most implementations of TCP, doing a \fIclose\fR\& does not guarantee that any data sent is delivered to the recipient before the close is detected at the remote side\&. If you want to guarantee delivery of the data to the recipient there are two common ways to achieve this\&. .RS 2 .TP 2 * Use \fIgen_tcp:shutdown(Sock, write)\fR\& to signal that no more data is to be sent and wait for the read side of the socket to be closed\&. .LP .TP 2 * Use the socket option \fI{packet, N}\fR\& (or something similar) to make it possible for the receiver to close the connection when it knowns it has received all the data\&. .LP .RE .RE .LP .nf .B connect(SockAddr, Opts) -> {ok, Socket} | {error, Reason} .br .fi .br .nf .B connect(SockAddr, Opts, Timeout) -> {ok, Socket} | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 SockAddr = socket:sockaddr_in() | socket:sockaddr_in6() .br Opts = [inet:inet_backend() | connect_option()] .br Timeout = timeout() .br Socket = socket() .br Reason = timeout | inet:posix() .br .RE .RE .RS .LP Connects to a server according to \fISockAddr\fR\&\&. This is primarily intended for link local IPv6 addresses (which require the scope-id), \fIsocket:sockaddr_in6()\fR\&\&. But for completeness, we also support IPv4, \fIsocket:sockaddr_in()\fR\&\&. .LP The \fIoptions\fR\& available are the same as for \fIconnect/3,4\fR\&\&. .LP .RS -4 .B Note: .RE Keep in mind that if the underlying OS \fIconnect()\fR\& call returns a timeout, \fIgen_tcp:connect\fR\& will also return a timeout (i\&.e\&. \fI{error, etimedout}\fR\&), even if a larger \fITimeout\fR\& was specified\&. .LP .RS -4 .B Note: .RE The default values for options specified to \fIconnect\fR\& can be affected by the Kernel configuration parameter \fIinet_default_connect_options\fR\&\&. For details, see \fIinet(3erl)\fR\&\&. .RE .LP .nf .B connect(Address, Port, Opts) -> {ok, Socket} | {error, Reason} .br .fi .br .nf .B connect(Address, Port, Opts, Timeout) -> .B {ok, Socket} | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Address = inet:socket_address() | inet:hostname() .br Port = inet:port_number() .br Opts = [inet:inet_backend() | connect_option()] .br Timeout = timeout() .br Socket = socket() .br Reason = timeout | inet:posix() .br .RE .RE .RS .LP Connects to a server on TCP port \fIPort\fR\& on the host with IP address \fIAddress\fR\&\&. Argument \fIAddress\fR\& can be a hostname or an IP address\&. .LP The following options are available: .RS 2 .TP 2 .B \fI{ip, Address}\fR\&: If the host has many network interfaces, this option specifies which one to use\&. .TP 2 .B \fI{ifaddr, Address}\fR\&: Same as \fI{ip, Address}\fR\&\&. If the host has many network interfaces, this option specifies which one to use\&. .RS 2 .LP However, if this instead is an \fIsocket:sockaddr_in()\fR\& or \fIsocket:sockaddr_in6()\fR\& this takes precedence over any value previously set with the \fIip\fR\& and \fIport\fR\& options\&. If these options (\fIip\fR\& or/and \fIport\fR\&) however comes \fIafter\fR\& this option, they may be used to \fIupdate\fR\& their corresponding fields of this options (for \fIip\fR\&, the \fIaddr\fR\& field, and for \fIport\fR\&, the \fIport\fR\& field)\&. .RE .TP 2 .B \fI{fd, integer() >= 0}\fR\&: If a socket has somehow been connected without using \fIgen_tcp\fR\&, use this option to pass the file descriptor for it\&. If \fI{ip, Address}\fR\& and/or \fI{port, port_number()}\fR\& is combined with this option, the \fIfd\fR\& is bound to the specified interface and port before connecting\&. If these options are not specified, it is assumed that the \fIfd\fR\& is already bound appropriately\&. .TP 2 .B \fIinet\fR\&: Sets up the socket for IPv4\&. .TP 2 .B \fIinet6\fR\&: Sets up the socket for IPv6\&. .TP 2 .B \fIlocal\fR\&: Sets up a Unix Domain Socket\&. See \fIinet:local_address()\fR\& .TP 2 .B \fI{port, Port}\fR\&: Specifies which local port number to use\&. .TP 2 .B \fI{tcp_module, module()}\fR\&: Overrides which callback module is used\&. Defaults to \fIinet_tcp\fR\& for IPv4 and \fIinet6_tcp\fR\& for IPv6\&. .TP 2 .B \fIOpt\fR\&: See \fIinet:setopts/2\fR\&\&. .RE .LP Packets can be sent to the returned socket \fISocket\fR\& using \fIsend/2\fR\&\&. Packets sent from the peer are delivered as messages: .LP .nf {tcp, Socket, Data} .fi .LP If the socket is in \fI{active, N}\fR\& mode (see \fIinet:setopts/2\fR\& for details) and its message counter drops to \fI0\fR\&, the following message is delivered to indicate that the socket has transitioned to passive (\fI{active, false}\fR\&) mode: .LP .nf {tcp_passive, Socket} .fi .LP If the socket is closed, the following message is delivered: .LP .nf {tcp_closed, Socket} .fi .LP If an error occurs on the socket, the following message is delivered (unless \fI{active, false}\fR\& is specified in the option list for the socket, in which case packets are retrieved by calling \fIrecv/2\fR\&): .LP .nf {tcp_error, Socket, Reason} .fi .LP The optional \fITimeout\fR\& parameter specifies a time-out in milliseconds\&. Defaults to \fIinfinity\fR\&\&. .LP .RS -4 .B Note: .RE Keep in mind that if the underlying OS \fIconnect()\fR\& call returns a timeout, \fIgen_tcp:connect\fR\& will also return a timeout (i\&.e\&. \fI{error, etimedout}\fR\&), even if a larger \fITimeout\fR\& was specified\&. .LP .RS -4 .B Note: .RE The default values for options specified to \fIconnect\fR\& can be affected by the Kernel configuration parameter \fIinet_default_connect_options\fR\&\&. For details, see \fIinet(3erl)\fR\&\&. .RE .LP .nf .B controlling_process(Socket, Pid) -> ok | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Socket = socket() .br Pid = pid() .br Reason = closed | not_owner | badarg | inet:posix() .br .RE .RE .RS .LP Assigns a new controlling process \fIPid\fR\& to \fISocket\fR\&\&. The controlling process is the process that receives messages from the socket\&. If called by any other process than the current controlling process, \fI{error, not_owner}\fR\& is returned\&. If the process identified by \fIPid\fR\& is not an existing local pid, \fI{error, badarg}\fR\& is returned\&. \fI{error, badarg}\fR\& may also be returned in some cases when \fISocket\fR\& is closed during the execution of this function\&. .LP If the socket is set in active mode, this function will transfer any messages in the mailbox of the caller to the new controlling process\&. If any other process is interacting with the socket while the transfer is happening, the transfer may not work correctly and messages may remain in the caller\&'s mailbox\&. For instance changing the sockets active mode before the transfer is complete may cause this\&. .RE .LP .nf .B listen(Port, Options) -> {ok, ListenSocket} | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Port = inet:port_number() .br Options = [inet:inet_backend() | listen_option()] .br ListenSocket = socket() .br Reason = system_limit | inet:posix() .br .RE .RE .RS .LP Sets up a socket to listen on port \fIPort\fR\& on the local host\&. .LP If \fIPort == 0\fR\&, the underlying OS assigns an available port number, use \fIinet:port/1\fR\& to retrieve it\&. .LP The following options are available: .RS 2 .TP 2 .B \fIlist\fR\&: Received \fIPacket\fR\& is delivered as a list\&. .TP 2 .B \fIbinary\fR\&: Received \fIPacket\fR\& is delivered as a binary\&. .TP 2 .B \fI{backlog, B}\fR\&: \fIB\fR\& is an integer >= \fI0\fR\&\&. The backlog value defines the maximum length that the queue of pending connections can grow to\&. Defaults to \fI5\fR\&\&. .TP 2 .B \fIinet6\fR\&: Sets up the socket for IPv6\&. .TP 2 .B \fIinet\fR\&: Sets up the socket for IPv4\&. .TP 2 .B \fI{fd, Fd}\fR\&: If a socket has somehow been connected without using \fIgen_tcp\fR\&, use this option to pass the file descriptor for it\&. .TP 2 .B \fI{ip, Address}\fR\&: If the host has many network interfaces, this option specifies which one to listen on\&. .TP 2 .B \fI{port, Port}\fR\&: Specifies which local port number to use\&. .TP 2 .B \fI{ifaddr, Address}\fR\&: Same as \fI{ip, Address}\fR\&\&. If the host has many network interfaces, this option specifies which one to use\&. .RS 2 .LP However, if this instead is an \fIsocket:sockaddr_in()\fR\& or \fIsocket:sockaddr_in6()\fR\& this takes precedence over any value previously set with the \fIip\fR\& and \fIport\fR\& options\&. If these options (\fIip\fR\& or/and \fIport\fR\&) however comes \fIafter\fR\& this option, they may be used to \fIupdate\fR\& their corresponding fields of this options (for \fIip\fR\&, the \fIaddr\fR\& field, and for \fIport\fR\&, the \fIport\fR\& field)\&. .RE .TP 2 .B \fI{tcp_module, module()}\fR\&: Overrides which callback module is used\&. Defaults to \fIinet_tcp\fR\& for IPv4 and \fIinet6_tcp\fR\& for IPv6\&. .TP 2 .B \fIOpt\fR\&: See \fIinet:setopts/2\fR\&\&. .RE .LP The returned socket \fIListenSocket\fR\& should be used in calls to \fIaccept/1,2\fR\& to accept incoming connection requests\&. .LP .RS -4 .B Note: .RE The default values for options specified to \fIlisten\fR\& can be affected by the Kernel configuration parameter \fIinet_default_listen_options\fR\&\&. For details, see \fIinet(3erl)\fR\&\&. .RE .LP .nf .B recv(Socket, Length) -> {ok, Packet} | {error, Reason} .br .fi .br .nf .B recv(Socket, Length, Timeout) -> {ok, Packet} | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Socket = socket() .br Length = integer() >= 0 .br Timeout = timeout() .br Packet = string() | binary() | HttpPacket .br Reason = closed | timeout | inet:posix() .br HttpPacket = term() .br .RS 2 See the description of \fIHttpPacket\fR\& in \fIerlang:decode_packet/3\fR\& in ERTS\&. .RE .RE .RE .RS .LP Receives a packet from a socket in \fIpassive\fR\& mode\&. A closed socket is indicated by return value \fI{error, closed}\fR\&\&. If the socket is not in passive mode, the return value is \fI{error, einval}\fR\&\&. .LP Argument \fILength\fR\& is only meaningful when the socket is in \fIraw\fR\& mode and denotes the number of bytes to read\&. If \fILength\fR\& is \fI0\fR\&, all available bytes are returned\&. If \fILength\fR\& > \fI0\fR\&, exactly \fILength\fR\& bytes are returned, or an error; possibly discarding less than \fILength\fR\& bytes of data when the socket is closed from the other side\&. .LP The optional \fITimeout\fR\& parameter specifies a time-out in milliseconds\&. Defaults to \fIinfinity\fR\&\&. .LP 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 \fIrecv\fR\& is not recommended as its behavior is dependent on the socket implementation, and could return errors such as \fI{error, ealready}\fR\&\&. .RE .LP .nf .B send(Socket, Packet) -> ok | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Socket = socket() .br Packet = iodata() .br Reason = closed | {timeout, RestData} | inet:posix() .br RestData = binary() .br .RE .RE .RS .LP Sends a packet on a socket\&. .LP There is no \fIsend\fR\& call with a time-out option, use socket option \fIsend_timeout\fR\& if time-outs are desired\&. See section Examples\&. .LP The return value \fI{error, {timeout, RestData}}\fR\& can only be returned when \fIinet_backend = socket\fR\&\&. .LP .RS -4 .B Note: .RE Non-blocking send\&. .LP If the user tries to send more data than there is room for in the OS send buffers, the \&'rest data\&' is put into (inet driver) internal buffers and later sent in the background\&. The function immediately returns ok (\fInot\fR\& informing the caller that not all of the data was actually sent)\&. Any issue while sending the \&'rest data\&' is maybe returned later\&. .LP When using \fIinet_backend = socket\fR\&, the behaviour is different\&. There is \fIno\fR\& buffering done (like the inet-driver does), instead the caller will "hang" until all of the data has been sent or send timeout (as specified by the \fIsend_timeout\fR\& option) expires (the function can hang even when using \&'inet\&' backend if the internal buffers are full)\&. .LP If this happens when using \fIpacket =/= raw\fR\&, we have a partial package written\&. A new package therefore \fImust not\fR\& be written at this point, as there is no way for the peer to distinguish this from the data portion of the current package\&. Instead, set package to raw, send the rest data (as raw data) and then set package to the wanted package type again\&. .RE .LP .nf .B shutdown(Socket, How) -> ok | {error, Reason} .br .fi .br .RS .LP Types: .RS 3 Socket = socket() .br How = read | write | read_write .br Reason = inet:posix() .br .RE .RE .RS .LP Closes a socket in one or two directions\&. .LP \fIHow == write\fR\& means closing the socket for writing, reading from it is still possible\&. .LP If \fIHow == read\fR\& or there is no outgoing data buffered in the \fISocket\fR\& port, the socket is shut down immediately and any error encountered is returned in \fIReason\fR\&\&. .LP If there is data buffered in the socket port, the attempt to shutdown the socket is postponed until that data is written to the kernel socket send buffer\&. If any errors are encountered, the socket is closed and \fI{error, closed}\fR\& is returned on the next \fIrecv/2\fR\& or \fIsend/2\fR\&\&. .LP Option \fI{exit_on_close, false}\fR\& is useful if the peer has done a shutdown on the write side\&. .LP .RS -4 .B Note: .RE Async shutdown write (write or read_write)\&. .LP If the shutdown attempt is made while the inet-driver is sending buffered data in the background, the shutdown is postponed until all buffered data has been sent\&. The function immediately returns \fIok\fR\& and the caller is \fInot\fR\& informed (that the shutdown has \fInot yet\fR\& been performed)\&. .LP When using \fIinet_backend = socket\fR\&, the behaviour is different\&. A shutdown with \fIHow == write | read_write\fR\&, the operation will take \fIimmediate\fR\& effect (unlike the inet-driver, which basically saves the operation for later)\&. .RE .SH "EXAMPLES" .LP The following example illustrates use of option \fI{active,once}\fR\& and multiple accepts by implementing a server as a number of worker processes doing accept on a single listening socket\&. Function \fIstart/2\fR\& takes the number of worker processes and the port number on which to listen for incoming connections\&. If \fILPort\fR\& is specified as \fI0\fR\&, an ephemeral port number is used, which is why the start function returns the actual port number allocated: .LP .nf 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. .fi .LP Example of a simple client: .LP .nf 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. .fi .LP The \fIsend\fR\& call does not accept a time-out option because time-outs on send is handled through socket option \fIsend_timeout\fR\&\&. 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 \fIsend\fR\& do like the following\&. .LP 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 \fIsend_timeout\fR\& can be used when connecting: .LP .nf \&... {ok,Sock} = gen_tcp:connect(HostAddress, Port, [{active,false}, {send_timeout, 5000}, {packet,2}]), loop(Sock), % See below \&... .fi .LP In the loop where requests are handled, send time-outs can now be detected: .LP .nf 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. .fi .LP 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 \fIsend_timeout\fR\& comes in handy\&.