1<?xml version="1.0" encoding="utf-8" ?>
2<!DOCTYPE erlref SYSTEM "erlref.dtd">
3
4<erlref>
5  <header>
6    <copyright>
7      <year>1997</year><year>2021</year>
8      <holder>Ericsson AB. All Rights Reserved.</holder>
9    </copyright>
10    <legalnotice>
11      Licensed under the Apache License, Version 2.0 (the "License");
12      you may not use this file except in compliance with the License.
13      You may obtain a copy of the License at
14
15          http://www.apache.org/licenses/LICENSE-2.0
16
17      Unless required by applicable law or agreed to in writing, software
18      distributed under the License is distributed on an "AS IS" BASIS,
19      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20      See the License for the specific language governing permissions and
21      limitations under the License.
22
23    </legalnotice>
24    <title>gen_tcp</title>
25    <prepared>tony@erix.ericsson.se</prepared>
26    <docno></docno>
27    <date>1997-10-24</date>
28    <rev>A</rev>
29  </header>
30  <module since="">gen_tcp</module>
31  <modulesummary>Interface to TCP/IP sockets.</modulesummary>
32  <description>
33    <p>This module provides functions for communicating
34      with sockets using the TCP/IP protocol.</p>
35    <p>The following code fragment is a simple example of
36      a client connecting to a server at port 5678, transferring a
37      binary, and closing the connection:</p>
38    <code type="none">
39client() ->
40    SomeHostInNet = "localhost", % to make it runnable on one machine
41    {ok, Sock} = gen_tcp:connect(SomeHostInNet, 5678,
42                                 [binary, {packet, 0}]),
43    ok = gen_tcp:send(Sock, "Some Data"),
44    ok = gen_tcp:close(Sock).</code>
45    <p>At the other end, a server is listening on port 5678, accepts
46      the connection, and receives the binary:</p>
47    <code type="none">
48server() ->
49    {ok, LSock} = gen_tcp:listen(5678, [binary, {packet, 0},
50                                        {active, false}]),
51    {ok, Sock} = gen_tcp:accept(LSock),
52    {ok, Bin} = do_recv(Sock, []),
53    ok = gen_tcp:close(Sock),
54    ok = gen_tcp:close(LSock),
55    Bin.
56
57do_recv(Sock, Bs) ->
58    case gen_tcp:recv(Sock, 0) of
59        {ok, B} ->
60            do_recv(Sock, [Bs, B]);
61        {error, closed} ->
62            {ok, list_to_binary(Bs)}
63    end.</code>
64    <p>For more examples, see section
65    <seeerl marker="#examples">Examples</seeerl>.</p>
66
67    <note>
68      <p>
69        Functions that create sockets can take an optional option;
70        <c>{inet_backend,&nbsp;Backend}</c> that, if specified,
71        has to be the first option.  This selects
72        the implementation backend towards the platform's socket API.
73      </p>
74      <p>
75        This is a <em>temporary</em> option
76        that will be ignored in a future release.
77      </p>
78      <p>
79        The default is <c>Backend&nbsp;=&nbsp;inet</c>
80        that selects the traditional <c>inet_drv.c</c> driver.
81        The other choice is <c>Backend&nbsp;=&nbsp;socket</c>
82        that selects the new <seeerl marker="socket"><c>socket</c></seeerl>
83        module and its NIF implementation.
84      </p>
85      <p>
86        The system default can be changed when the node is started
87        with the application <c>kernel</c>'s configuration variable
88        <c>inet_backend</c>.
89      </p>
90      <p>For <c>gen_tcp</c> with <c>inet_backend = socket</c> we have tried
91      to be as "compatible" as possible which has sometimes been impossible.
92      Here is a list of cases when the behaviour of inet-backend
93      <c>inet</c> (default) and <c>socket</c> are different: </p>
94      <list type="bulleted">
95        <item>
96	  <p><seeerl marker="#non_blocking_send">Non-blocking send</seeerl></p>
97	  <p>If a user calling
98	  <seemfa marker="#send/2"><c>gen_tcp:send/2</c></seemfa>
99	  with <c>inet_backend = inet</c>,
100	  tries to send more data than there is room for in the OS buffers,
101	  the "rest data" is buffered by the inet driver (and later sent in the
102	  background).
103	  The effect for the user is that the call is non-blocking.</p>
104	  <p>This is <em>not</em> the effect when
105	  <c>inet_backend = socket</c>, since there is no buffering.
106	  Instead the user hangs either until all data has been sent or the
107	  <c>send_timeout</c> timeout has been reached. </p>
108	</item>
109
110	<item><p>Remote close detected by background send. </p>
111	<p>An background send will detect a 'remote close' and
112	(the inet driver will) mark the socket as 'closed'.
113	No other action is taken.
114	If the socket has <c>active</c> set to <c>false</c> (passive) at
115	this point and no one is reading, this will not be noticed.
116	But as soon as the socket is "activated" (<c>active</c> set to
117	not <c>false</c>,
118	<seemfa marker="#send/2">send/2</seemfa>
119	is called or
120	<seemfa marker="#recv/2">recv/2,3</seemfa>
121	is called),
122	an error message will be sent to the
123	caller or (socket) owner: <c>{tcp_error, Socket, econnreset}</c>.
124	Any data in the OS receive buffers will be lost! </p>
125	<p>This behaviour is <em>not</em> replicated by the socket
126	implementation.
127	A send operation will detect a remote close and immediately
128	return this to the caller, but do nothing else.
129	A reader will therefor be able to extract any data from the OS buffers.
130	If the socket is set to <c>active</c> to not <c>false</c>, the data
131	will be received as expected (<c>{tcp, ...}</c> and then a closed
132	message (<c>{tcp_closed, ...}</c> will be received (not an error). </p>
133	</item>
134
135        <item>
136	  <p>The option
137	  <seeerl marker="inet#option-show_econnreset">show_econnreset</seeerl>
138	  basically do <em>not</em>
139	  work as described when used with <c>inet_backend = socket</c>.
140	  The "issue" is that a remote close (as described above)
141	  <em>do</em> allow a reader to extract what is in the read buffers
142	  before a close is "delivered".</p>
143	</item>
144
145        <item>
146	  <p>The option
147	  <seeerl marker="inet#option-nodelay">nodelay</seeerl>
148	  is a TCP specific option that is <em>not</em> compatible with
149	  <c>domain = local</c>. </p>
150	  <p>When using <c>inet_backend = socket</c>, trying to create a socket
151	  (via listen or connect) with <c>domain = local</c>
152	  (for example with option {ifaddr, {local,"/tmp/test"}})
153	  <em>will fail</em> with <c>{error, enotsup}</c>. </p>
154	  <p>This does not actually work for <c>inet_backend = inet</c> either,
155	  but in that case the error is simply <em>ignored</em>,
156	  which is a <em>bad</em> idea. We have choosen to <em>not</em>
157	  ignore this error for <c>inet_backend = socket</c>. </p>
158	</item>
159
160	<item>
161	  <p><seeerl marker="#async_shutdown_write">Async shutdown write</seeerl></p>
162	  <p>Calling
163	  <seemfa marker="#shutdown/2">gen_tcp:shutdown(Socket, write | read_write)</seemfa>
164	  on a socket created with <c>inet_backend = socket</c>
165	  will take <em>immediate</em> effect,
166	  unlike for a socket created with <c>inet_backend = inet</c>.</p>
167	  <p>See <seeerl marker="#async_shutdown_write">async shutdown write</seeerl>
168	  for more info. </p>
169	</item>
170      </list>
171    </note>
172  </description>
173
174  <datatypes>
175    <datatype>
176      <name name="option"/>
177    </datatype>
178    <datatype>
179      <name name="pktoptions_value"/>
180      <desc>
181	<p>
182	  If the platform implements the IPv4 option
183	  <c>IP_PKTOPTIONS</c>, or the IPv6 option
184	  <c>IPV6_PKTOPTIONS</c> or <c>IPV6_2292PKTOPTIONS</c> for the socket
185	  this value is returned from
186	  <seemfa marker="inet#getopts/2"><c>inet:getopts/2</c></seemfa>
187	  when called with the option name
188	  <seetype marker="#option_name"><c>pktoptions</c></seetype>.
189	</p>
190	<note>
191	  <p>
192	    This option appears to be VERY Linux specific,
193	    and its existence in future Linux kernel versions
194	    is also worrying since the option is part of RFC 2292
195	    which is since long (2003) obsoleted by RFC 3542
196	    that <em>explicitly</em> removes this possibility to get
197	    packet information from a stream socket.
198	    For comparision: it has existed in FreeBSD but is now removed,
199	    at least since FreeBSD 10.
200	  </p>
201	</note>
202      </desc>
203    </datatype>
204    <datatype>
205      <name name="option_name"/>
206    </datatype>
207    <datatype>
208      <name name="connect_option"/>
209    </datatype>
210    <datatype>
211      <name name="listen_option"/>
212    </datatype>
213    <datatype>
214      <name>socket()</name>
215      <desc><p>As returned by
216        <seemfa marker="#accept/1"><c>accept/1,2</c></seemfa> and
217        <seemfa marker="#connect/3"><c>connect/3,4</c></seemfa>.</p>
218        <marker id="connect"></marker>
219      </desc>
220    </datatype>
221  </datatypes>
222
223  <funcs>
224    <func>
225      <name name="accept" arity="1" since=""/>
226      <name name="accept" arity="2" since=""/>
227      <fsummary>Accept an incoming connection request on a listening socket.</fsummary>
228      <type_desc variable="ListenSocket">Returned by
229        <seemfa marker="#listen/2"><c>listen/2</c></seemfa>.
230      </type_desc>
231      <desc>
232        <p>Accepts an incoming connection request on a listening socket.
233          <c><anno>Socket</anno></c> must be a socket returned from
234          <seemfa marker="#listen/2"><c>listen/2</c></seemfa>.
235          <c><anno>Timeout</anno></c> specifies a time-out value in
236          milliseconds. Defaults to <c>infinity</c>.</p>
237        <p>Returns:</p>
238        <list type="bulleted">
239          <item><p><c>{ok, <anno>Socket</anno>}</c> if a connection is
240            established</p></item>
241          <item><p><c>{error, closed}</c> if <c><anno>ListenSocket</anno></c>
242            is closed</p></item>
243          <item><p><c>{error, timeout}</c> if no connection is established
244            within the specified time</p></item>
245          <item><p><c>{error, system_limit}</c> if all available ports in the
246            Erlang emulator are in use</p></item>
247          <item><p>A POSIX error value if something else goes wrong, see
248            <seeerl marker="inet"><c>inet(3)</c></seeerl> for possible
249            error values</p></item>
250        </list>
251        <p>Packets can be sent to the returned socket <c><anno>Socket</anno></c>
252          using
253          <seemfa marker="#send/2"><c>send/2</c></seemfa>.
254          Packets sent from the peer are delivered as messages (unless
255          <c>{active, false}</c> is specified in the option list for the
256          listening socket, in which case packets are retrieved by calling
257          <seemfa marker="#recv/2"><c>recv/2</c></seemfa>):</p>
258        <code type="none">
259{tcp, Socket, Data}</code>
260        <note>
261          <p>The <c>accept</c> call does
262            <em>not</em> have to be issued from the socket owner
263            process. Using version 5.5.3 and higher of the emulator,
264            multiple simultaneous accept calls can be issued from
265            different processes, which allows for a pool of acceptor
266            processes handling incoming connections.</p>
267        </note>
268      </desc>
269    </func>
270
271    <func>
272      <name name="close" arity="1" since=""/>
273      <fsummary>Close a TCP socket.</fsummary>
274      <desc>
275        <p>Closes a TCP socket.</p>
276        <p>Note that in most implementations of TCP, doing a <c>close</c> does
277         not guarantee that any data sent is delivered to the recipient before
278         the close is detected at the remote side. If you want to guarantee
279         delivery of the data to the recipient there are two common ways to
280         achieve this.</p>
281         <list type="ordered">
282           <item><p>Use <seemfa marker="#shutdown/2">
283             <c>gen_tcp:shutdown(Sock, write)</c></seemfa> to signal that
284             no more data is to be sent and wait for the read side of the
285             socket to be closed.</p>
286           </item>
287           <item><p>Use the socket option <seeerl marker="inet#packet">
288             <c>{packet, N}</c></seeerl> (or something similar) to make
289             it possible for the receiver to close the connection when it
290             knowns it has received all the data.</p>
291           </item>
292         </list>
293      </desc>
294    </func>
295
296    <func>
297      <name name="connect" arity="3" since=""/>
298      <name name="connect" arity="4" since=""/>
299      <fsummary>Connect to a TCP port.</fsummary>
300      <desc>
301        <p>Connects to a server on TCP port <c><anno>Port</anno></c> on the host
302          with IP address <c><anno>Address</anno></c>. Argument
303          <c><anno>Address</anno></c> can be a hostname or an IP address.</p>
304        <p>The following options are available:</p>
305        <taglist>
306          <tag><c>{ip, Address}</c></tag>
307          <item><p>If the host has many network interfaces, this option
308            specifies which one to use.</p></item>
309          <tag><c>{ifaddr, Address}</c></tag>
310          <item><p>Same as <c>{ip, Address}</c>. If the host has many
311            network interfaces, this option specifies which one to use.</p>
312          </item>
313          <tag><c>{fd, integer() >= 0}</c></tag>
314          <item><p>If a socket has somehow been connected without using
315            <c>gen_tcp</c>, use this option to pass the file descriptor
316            for it. If <c>{ip, Address}</c> and/or
317            <c>{port, port_number()}</c> is combined with this option,  the
318            <c>fd</c> is bound to the specified interface and port before
319            connecting. If these options are not specified, it is assumed that
320            the <c>fd</c> is already bound appropriately.</p></item>
321          <tag><c>inet</c></tag>
322          <item><p>Sets up the socket for IPv4.</p></item>
323          <tag><c>inet6</c></tag>
324          <item><p>Sets up the socket for IPv6.</p></item>
325	  <tag><c>local</c></tag>
326	  <item>
327            <p>
328	      Sets up a Unix Domain Socket. See
329	      <seetype marker="inet#local_address">
330		<c>inet:local_address()</c>
331	      </seetype>
332	    </p>
333          </item>
334          <tag><c>{port, Port}</c></tag>
335          <item><p>Specifies which local port number to use.</p></item>
336          <tag><c>{tcp_module, module()}</c></tag>
337          <item><p>Overrides which callback module is used. Defaults to
338            <c>inet_tcp</c> for IPv4 and <c>inet6_tcp</c> for IPv6.</p></item>
339          <tag><c>Opt</c></tag>
340          <item><p>See
341            <seemfa marker="inet#setopts/2"><c>inet:setopts/2</c></seemfa>.</p>
342          </item>
343        </taglist>
344        <p>Packets can be sent to the returned socket <c><anno>Socket</anno></c>
345          using <seemfa marker="#send/2"><c>send/2</c></seemfa>.
346          Packets sent from the peer are delivered as messages:</p>
347        <code type="none">
348{tcp, Socket, Data}</code>
349        <p>If the socket is in <c>{active, N}</c> mode (see
350          <seemfa marker="inet#setopts/2"><c>inet:setopts/2</c></seemfa>
351          for details) and its message counter drops to <c>0</c>, the following
352          message is delivered to indicate that the
353          socket has transitioned to passive (<c>{active, false}</c>) mode:</p>
354        <code type="none">
355{tcp_passive, Socket}</code>
356        <p>If the socket is closed, the following message is delivered:</p>
357        <code type="none">
358{tcp_closed, Socket}</code>
359        <p>If an error occurs on the socket, the following message is delivered
360          (unless <c>{active, false}</c> is specified in the option list for
361          the socket, in which case packets are retrieved by calling
362          <seemfa marker="#recv/2"><c>recv/2</c></seemfa>):</p>
363        <code type="none">
364{tcp_error, Socket, Reason}</code>
365        <p>The optional <c><anno>Timeout</anno></c> parameter specifies a
366          time-out in milliseconds. Defaults to <c>infinity</c>.</p>
367        <note>
368          <p>Keep in mind that if the underlying OS <c>connect()</c> call returns
369            a timeout, <c>gen_tcp:connect</c> will also return a timeout
370            (i.e. <c>{error, etimedout}</c>), even if a larger <c>Timeout</c> was
371            specified.</p>
372        </note>
373        <note>
374          <p>The default values for options specified to <c>connect</c> can
375            be affected by the Kernel configuration parameter
376            <c>inet_default_connect_options</c>. For details, see
377            <seeerl marker="inet"><c>inet(3)</c></seeerl>.</p>
378        </note>
379      </desc>
380    </func>
381
382    <func>
383      <name name="controlling_process" arity="2" since=""/>
384      <fsummary>Change controlling process of a socket.</fsummary>
385      <desc>
386        <p>Assigns a new controlling process <c><anno>Pid</anno></c> to
387          <c><anno>Socket</anno></c>. The controlling process is the process
388          that receives messages from the socket. If called by any other
389          process than the current controlling process,
390          <c>{error, not_owner}</c> is returned. If the process identified
391          by <c><anno>Pid</anno></c> is not an existing local pid,
392          <c>{error, badarg}</c> is returned. <c>{error, badarg}</c> may also
393          be returned in some cases when <c><anno>Socket</anno></c> is closed
394          during the execution of this function.</p>
395          <p>If the socket is set in active mode, this function
396          will transfer any messages in the mailbox of the caller
397          to the new controlling process.
398          If any other process is interacting with the socket while
399          the transfer is happening, the transfer may not work correctly
400          and messages may remain in the caller's mailbox. For instance
401          changing the sockets active mode before the transfer is complete
402          may cause this.</p>
403      </desc>
404    </func>
405
406    <func>
407      <name name="listen" arity="2" since=""/>
408      <fsummary>Set up a socket to listen on a port.</fsummary>
409      <desc>
410        <p>Sets up a socket to listen on port <c><anno>Port</anno></c> on
411          the local host.</p>
412        <p>If <c><anno>Port</anno> == 0</c>, the underlying OS assigns an
413          available port number, use
414          <seemfa marker="inet#port/1"><c>inet:port/1</c></seemfa>
415          to retrieve it.</p>
416        <p>The following options are available:</p>
417        <taglist>
418          <tag><c>list</c></tag>
419          <item><p>Received <c>Packet</c> is delivered as a list.</p></item>
420          <tag><c>binary</c></tag>
421          <item><p>Received <c>Packet</c> is delivered as a binary.</p></item>
422          <tag><c>{backlog, B}</c></tag>
423          <item><p><c>B</c> is an integer &gt;= <c>0</c>. The backlog value
424            defines the maximum length that the queue of pending connections
425            can grow to. Defaults to <c>5</c>.</p></item>
426          <tag><c>{ip, Address}</c></tag>
427          <item><p>If the host has many network interfaces, this option
428            specifies which one to listen on.</p></item>
429          <tag><c>{port, Port}</c></tag>
430          <item><p>Specifies which local port number to use.</p></item>
431          <tag><c>{fd, Fd}</c></tag>
432          <item><p>If a socket has somehow been connected without using
433            <c>gen_tcp</c>, use this option to pass the file
434            descriptor for it.</p></item>
435          <tag><c>{ifaddr, Address}</c></tag>
436          <item><p>Same as <c>{ip, Address}</c>. If the host has many
437            network interfaces, this option specifies which one to use.</p>
438          </item>
439          <tag><c>inet6</c></tag>
440          <item><p>Sets up the socket for IPv6.</p></item>
441          <tag><c>inet</c></tag>
442          <item><p>Sets up the socket for IPv4.</p></item>
443          <tag><c>{tcp_module, module()}</c></tag>
444          <item><p>Overrides which callback module is used. Defaults to
445            <c>inet_tcp</c> for IPv4 and <c>inet6_tcp</c> for IPv6.</p></item>
446          <tag><c>Opt</c></tag>
447          <item><p>See
448            <seemfa marker="inet#setopts/2"><c>inet:setopts/2</c></seemfa>.
449            </p></item>
450        </taglist>
451        <p>The returned socket <c><anno>ListenSocket</anno></c> should be used
452          in calls to <seemfa marker="#accept/1"><c>accept/1,2</c></seemfa> to
453          accept incoming connection requests.</p>
454        <note>
455          <p>The default values for options specified to <c>listen</c> can
456            be affected by the Kernel configuration parameter
457            <c>inet_default_listen_options</c>. For details, see
458            <seeerl marker="inet"><c>inet(3)</c></seeerl>.</p>
459        </note>
460      </desc>
461    </func>
462
463    <func>
464      <name name="recv" arity="2" since=""/>
465      <name name="recv" arity="3" since=""/>
466      <fsummary>Receive a packet from a passive socket.</fsummary>
467      <type_desc variable="HttpPacket">See the description of
468        <c>HttpPacket</c> in
469        <seemfa marker="erts:erlang#decode_packet/3"><c>erlang:decode_packet/3</c></seemfa>
470      in ERTS.
471      </type_desc>
472      <desc>
473        <p>Receives a packet from a socket in passive
474          mode. A closed socket is indicated by return value
475          <c>{error, closed}</c>.</p>
476        <p>Argument <c><anno>Length</anno></c> is only meaningful when
477          the socket is in <c>raw</c> mode and denotes the number of
478          bytes to read. If <c><anno>Length</anno></c> is <c>0</c>, all
479          available bytes are returned.
480          If <c><anno>Length</anno></c> &gt; <c>0</c>, exactly
481          <c><anno>Length</anno></c> bytes are returned, or an error;
482          possibly discarding less than <c><anno>Length</anno></c> bytes of
483          data when the socket is closed from the other side.</p>
484        <p>The optional <c><anno>Timeout</anno></c> parameter specifies a
485          time-out in milliseconds. Defaults to <c>infinity</c>.</p>
486      </desc>
487    </func>
488
489    <func>
490      <name name="send" arity="2" since=""/>
491      <fsummary>Send a packet.</fsummary>
492      <desc>
493        <p>Sends a packet on a socket.</p>
494        <p>There is no <c>send</c> call with a time-out option, use socket
495        option <c>send_timeout</c> if time-outs are desired. See section
496        <seeerl marker="#examples">Examples</seeerl>.</p>
497	<p>The return value <c>{error, {timeout, RestData}}</c> can
498	only be returned when <c>inet_backend = socket</c>. </p>
499        <marker id="non_blocking_send"></marker>
500        <note>
501          <p>Non-blocking send.</p>
502          <p>If the user tries to send more data than there is room for
503          in the OS send buffers, the 'rest data' is put into (inet driver)
504          internal buffers and later sent in the background.
505          The function immediately returns ok (<em>not</em> informing the
506          caller that not all of the data was actually sent).
507          Any issue while sending the 'rest data' is maybe returned later. </p>
508          <p>When using <c>inet_backend = socket</c>, the
509          behaviour is different. There is <em>no</em>
510          buffering done (like the inet-driver does), instead
511          the caller will "hang" until all of the data has been sent or
512          send timeout (as specified by the <c>send_timeout</c> option)
513          expires (the function can hang even when using 'inet' backend
514          if the internal buffers are full). </p>
515	  <p>If this happens when using <c>packet =/= raw</c>, we have a partial
516	  package written. A new package therefor <em>must not</em> be written
517	  at this point, as there is no way for the peer to distinguish this
518	  from the data portion of the current package. Instead, set package
519	  to raw, send the rest data (as raw data) and then set package to
520	  the wanted package type again. </p>
521        </note>
522      </desc>
523    </func>
524
525    <func>
526      <name name="shutdown" arity="2" since=""/>
527      <fsummary>Asynchronously close a socket.</fsummary>
528      <desc>
529        <p>Closes a socket in one or two directions.</p>
530        <p><c><anno>How</anno> == write</c> means closing the socket for
531          writing, reading from it is still possible.</p>
532        <p>If <c><anno>How</anno> == read</c> or there is no outgoing
533          data buffered in the <c><anno>Socket</anno></c> port,
534          the socket is shut down immediately and any error encountered
535          is returned in <c><anno>Reason</anno></c>.</p>
536        <p>If there is data buffered in the socket port, the attempt
537          to shutdown the socket is postponed until that data is written to the
538          kernel socket send buffer. If any errors are encountered, the socket
539          is closed and <c>{error, closed}</c> is returned on the next
540          <seemfa marker="#recv/2"><c>recv/2</c></seemfa> or
541          <seemfa marker="#send/2"><c>send/2</c></seemfa>.</p>
542        <p>Option <c>{exit_on_close, false}</c> is useful if the peer has done
543          a shutdown on the write side.</p>
544        <marker id="async_shutdown_write"></marker>
545        <note>
546          <p>Async shutdown write (write or read_write).</p>
547          <p>If the shutdown attempt is made while the inet-driver
548	  is sending buffered data in the background,
549	  the shutdown is postponed until all buffered data has been sent.
550	  The function immediately returns <c>ok</c> and the caller is
551          <em>not</em> informed (that the shutdown has <em>not yet</em>
552          been performed). </p>
553          <p>When using <c>inet_backend = socket</c>, the
554          behaviour is different. A shutdown with
555          <c>How == write | read_write</c>, the operation will
556          take <em>immediate</em> effect (unlike the inet-driver,
557	  which basically saves the operation for later). </p>
558        </note>
559      </desc>
560    </func>
561  </funcs>
562
563  <section>
564    <title>Examples</title>
565    <marker id="examples"></marker>
566    <p>The following example illustrates use of option
567    <c>{active,once}</c> and multiple accepts by implementing a server
568    as a number of worker processes doing accept on a single listening
569    socket. Function <c>start/2</c> takes the number of worker
570    processes and the port number on which to listen for incoming
571    connections. If <c>LPort</c> is specified as <c>0</c>, an
572    ephemeral port number is used, which is why the start function
573    returns the actual port number allocated:</p>
574    <code type="none">
575start(Num,LPort) ->
576    case gen_tcp:listen(LPort,[{active, false},{packet,2}]) of
577        {ok, ListenSock} ->
578            start_servers(Num,ListenSock),
579            {ok, Port} = inet:port(ListenSock),
580            Port;
581        {error,Reason} ->
582            {error,Reason}
583    end.
584
585start_servers(0,_) ->
586    ok;
587start_servers(Num,LS) ->
588    spawn(?MODULE,server,[LS]),
589    start_servers(Num-1,LS).
590
591server(LS) ->
592    case gen_tcp:accept(LS) of
593        {ok,S} ->
594            loop(S),
595            server(LS);
596        Other ->
597            io:format("accept returned ~w - goodbye!~n",[Other]),
598            ok
599    end.
600
601loop(S) ->
602    inet:setopts(S,[{active,once}]),
603    receive
604        {tcp,S,Data} ->
605            Answer = process(Data), % Not implemented in this example
606            gen_tcp:send(S,Answer),
607            loop(S);
608        {tcp_closed,S} ->
609            io:format("Socket ~w closed [~w]~n",[S,self()]),
610            ok
611    end.</code>
612    <p>Example of a simple client:</p>
613    <code type="none">
614client(PortNo,Message) ->
615    {ok,Sock} = gen_tcp:connect("localhost",PortNo,[{active,false},
616                                                    {packet,2}]),
617    gen_tcp:send(Sock,Message),
618    A = gen_tcp:recv(Sock,0),
619    gen_tcp:close(Sock),
620    A.</code>
621    <p>The <c>send</c> call does not accept a time-out
622      option because time-outs on send is handled through socket
623      option <c>send_timeout</c>. The behavior of a send operation with
624      no receiver is mainly defined by the underlying TCP
625      stack and the network infrastructure. To write
626      code that handles a hanging receiver that can eventually cause
627      the sender to hang on a <c>send</c> do like the following.</p>
628    <p>Consider a process that receives data from a client process
629      to be forwarded to a server on the network. The process is
630      connected to the server through TCP/IP and does not get any acknowledge
631      for each message it sends, but has to rely on the send time-out
632      option to detect that the other end is unresponsive. Option
633      <c>send_timeout</c> can be used when connecting:</p>
634    <code type="none">
635...
636{ok,Sock} = gen_tcp:connect(HostAddress, Port,
637                            [{active,false},
638                             {send_timeout, 5000},
639                             {packet,2}]),
640                loop(Sock), % See below
641...</code>
642    <p>In the loop where requests are handled, send time-outs can now be
643      detected:</p>
644    <code type="none">
645loop(Sock) ->
646    receive
647        {Client, send_data, Binary} ->
648            case gen_tcp:send(Sock,[Binary]) of
649                {error, timeout} ->
650                    io:format("Send timeout, closing!~n",
651                              []),
652                    handle_send_timeout(), % Not implemented here
653                    Client ! {self(),{error_sending, timeout}},
654                    %% Usually, it's a good idea to give up in case of a
655                    %% send timeout, as you never know how much actually
656                    %% reached the server, maybe only a packet header?!
657                    gen_tcp:close(Sock);
658                {error, OtherSendError} ->
659                    io:format("Some other error on socket (~p), closing",
660                              [OtherSendError]),
661                    Client ! {self(),{error_sending, OtherSendError}},
662                    gen_tcp:close(Sock);
663                ok ->
664                    Client ! {self(), data_sent},
665                    loop(Sock)
666            end
667    end.</code>
668    <p>Usually it suffices to detect time-outs on receive, as most
669      protocols include some sort of acknowledgment from the server,
670      but if the protocol is strictly one way, option <c>send_timeout</c>
671      comes in handy.</p>
672  </section>
673</erlref>
674
675