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
Functions that create sockets can take an optional option;
This is a temporary option that will be ignored in a future release.
The default is
The system default can be changed when the node is started
with the application
For
If a user calling
This is not the effect when
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
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 therefor be able to extract any data from the OS buffers.
If the socket is set to
The option
The option
When using
This does not actually work for
Calling
See
If the platform implements the IPv4 option
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 comparision: it has existed in FreeBSD but is now removed, at least since FreeBSD 10.
As returned by
Accepts an incoming connection request on a listening socket.
Returns:
A POSIX error value if something else goes wrong, see
Packets can be sent to the returned socket
{tcp, Socket, Data}
The
Closes a TCP socket.
Note that in most implementations of TCP, doing a
Use
Use the socket option
Connects to a server according to
The
Keep in mind that if the underlying OS
The default values for options specified to
Connects to a server on TCP port
The following options are available:
If the host has many network interfaces, this option specifies which one to use.
Same as
However, if this instead is an
If a socket has somehow been connected without using
Sets up the socket for IPv4.
Sets up the socket for IPv6.
Sets up a Unix Domain Socket. See
Specifies which local port number to use.
Overrides which callback module is used. Defaults to
See
Packets can be sent to the returned socket
{tcp, Socket, Data}
If the socket is in
{tcp_passive, Socket}
If the socket is closed, the following message is delivered:
{tcp_closed, Socket}
If an error occurs on the socket, the following message is delivered
(unless
{tcp_error, Socket, Reason}
The optional
Keep in mind that if the underlying OS
The default values for options specified to
Assigns a new controlling process
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.
Sets up a socket to listen on port
If
The following options are available:
Received
Received
Sets up the socket for IPv6.
Sets up the socket for IPv4.
If a socket has somehow been connected without using
If the host has many network interfaces, this option specifies which one to listen on.
Specifies which local port number to use.
Same as
However, if this instead is an
Overrides which callback module is used. Defaults to
See
The returned socket
The default values for options specified to
Receives a packet from a socket in passive
mode. A closed socket is indicated by return value
Argument
The optional
Sends a packet on a socket.
There is no
The return value
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 put into (inet driver) internal buffers and later sent in the background. The function immediately returns ok (not informing the caller that not all of the data was actually sent). Any issue while sending the 'rest data' is maybe returned later.
When using
If this happens when using
Closes a socket in one or two directions.
If
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
Option
Async shutdown write (write or read_write).
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
When using
The following example illustrates use of option
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
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
...
{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