gsocket: Enable TCP_NODELAY by default for stream GSockets

`TCP_NODELAY` disables Nagle’s algorithm, which is generally a better
default for modern networks than having it enabled. Nagle’s algorithm
delays sending small data blobs until they fill an entire TCP segment,
so as to amortise the cost of sending the segment.

This improves bandwidth at the cost of latency. Given the large
bandwidth capabilities of most modern networks, most streams are
constrained by latency rather than bandwidth, so disabling Nagle’s
algorithm makes sense.

Various other major bits of software (such as libcurl) already disable
Nagle’s algorithm by default.

Specific applications which need it can turn it back on by calling
`g_socket_set_option()`.

Signed-off-by: Philip Withnall <pwithnall@gnome.org>

Fixes: #791
This commit is contained in:
Philip Withnall 2023-11-29 17:08:10 +00:00
parent 641bea17f2
commit 039876e6d9

View File

@ -138,6 +138,24 @@
* a `GSocket` concurrently from multiple threads, you must implement your own
* locking.
*
* ## Nagles algorithm
*
* Since GLib 2.80, `GSocket` will automatically set the `TCP_NODELAY` option on
* all `G_SOCKET_TYPE_STREAM` sockets. This disables
* [Nagles algorithm](https://en.wikipedia.org/wiki/Nagle%27s_algorithm) as it
* typically does more harm than good on modern networks.
*
* If your application needs Nagles algorithm enabled, call
* [method@Gio.Socket.set_option] after constructing a `GSocket` to enable it:
* ```c
* socket = g_socket_new (, G_SOCKET_TYPE_STREAM, );
* if (socket != NULL)
* {
* g_socket_set_option (socket, IPPROTO_TCP, TCP_NODELAY, FALSE, &local_error);
* // handle error if needed
* }
* ```
*
* Since: 2.22
*/
@ -749,6 +767,8 @@ g_socket_constructed (GObject *object)
/* See note about SIGPIPE below. */
g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
#endif
if (socket->priv->type == G_SOCKET_TYPE_STREAM)
g_socket_set_option (socket, IPPROTO_TCP, TCP_NODELAY, TRUE, NULL);
}
}