std.net.socket
IP and Unix domain sockets.
This module provides types for various socket types, such as TCP, UDP and Unix sockets.
The types Socket
and UnixSocket
are low-level sockets that implement most
of the socket logic. Types such as TcpServer
and TcpClient
wrap these
sockets to make it easier to create commonly used sockets, such as a TCP
client.
Deadlines and timeouts
Socket timeouts are supported through a mechanism known as a "deadline". A
deadline specifies the time after which socket operations must time out when
waiting for them to complete. Deadlines represent a fixed point in time, and
can be created from both Duration
and Instant
values.
The use of deadlines instead of timeouts makes it easier to apply time limits to multiple operations. Consider the following chain of events:
read()
write()
read()
Traditionally one might set a timeout such as 10 seconds. This poses a problem: the timeout is applied to every operation, meaning each operation is allowed to run up to 10 seconds, resulting in a total maximum runtime of 30 seconds.
Using deadlines one sets a deadline in the future, and no matter the amount of operations performed, the operations time out once we cross the deadline. In our above example that means we can easily limit the total runtime to 10 seconds using a deadline that's 10 seconds in the future.
Deadlines are set using Socket.timeout_after
and
UnixSocket.timeout_after=
. Here's an example using deadlines to limit the
time spent waiting for a client to connect:
import std.net.ip (IpAddress)
import std.net.socket (TcpServer)
import std.time (Duration)
let server = TcpServer.new(ip: IpAddress.v4(0, 0, 0, 0), port: 9000).get
server.socket.timeout_after = Duration.from_secs(3)
# This times out after roughly three seconds.
server.accept.get
It's important to keep in mind that deadlines only apply when an operation must wait, i.e. a read is performed but no data is available. If the operation completes immediately (i.e. a read is performed and enough data is available), the deadline is ignored. This means that if you perform an operation in a loop and set a deadline, and data is always available such that the operation never blocks, the loop may run indefinitely; depending on what the loop does of course.
For more information about timeouts versus deadlines, consider reading this article.
Classes
Socket | A low-level, non-blocking IPv4 or IPv6 socket. | |
SocketAddress | An IPv4 or IPv6 socket address. | |
TcpClient | A TCP socket connected to another TCP socket. | |
TcpServer | A TCP socket server that can accept incoming connections. | |
UdpSocket | A UDP socket. | |
UnixAddress | A Unix domain socket address. | |
UnixClient | A Unix stream socket connected to another Unix socket. | |
UnixDatagram | A Unix datagram socket. | |
UnixServer | A Unix socket server that can accept incoming connections. | |
UnixSocket | A low-level, non-blocking Unix domain socket. |