Description
This module provides functions for communicating with sockets using the TCP/IP protocol.
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 is Backend = inet
that selects the traditional inet_drv.c
driver. The other choice is Backend = socket
that selects the new socket
module and its NIF implementation.
The system default can be changed when the node is started with the application kernel
's configuration variable inet_backend
.
For gen_tcp
with inet_backend = socket
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 inet
(default) and socket
are different:
-
Non-blocking send
If a user calling gen_tcp:send/2
with inet_backend = inet
, 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.
This is not the effect when inet_backend = socket
, since there is no buffering. Instead the user hangs either until all data has been sent or the send_timeout
timeout has been reached.
-
Remote close detected by background send.
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 active
set to false
(passive) at this point and no one is reading, this will not be noticed. But as soon as the socket is "activated" (active
set to not false
, send/2
is called or recv/2,3
is called), an error message will be sent to the caller or (socket) owner: {tcp_error, Socket, econnreset}
. Any data in the OS receive buffers will be lost!
This behaviour is not 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 active
to not false
, the data will be received as expected ({tcp, ...}
and then a closed message ({tcp_closed, ...}
will be received (not an error).
-
The option show_econnreset
basically do not work as described when used with inet_backend = socket
. The "issue" is that a remote close (as described above) do allow a reader to extract what is in the read buffers before a close is "delivered".
-
The option nodelay
is a TCP specific option that is not compatible with domain = local
.
When using inet_backend = socket
, trying to create a socket (via listen or connect) with domain = local
(for example with option {ifaddr, {local,"/tmp/test"}}) will fail with {error, enotsup}
.
This does not actually work for inet_backend = inet
either, but in that case the error is simply ignored, which is a bad idea. We have chosen to not ignore this error for inet_backend = socket
.
-
Async shutdown write
Calling gen_tcp:shutdown(Socket, write | read_write)
on a socket created with inet_backend = socket
will take immediate effect, unlike for a socket created with inet_backend = inet
.
See async shutdown write
for more info.
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.