Skip to content

Commit c3a3ac1

Browse files
server: set TCP.NODELAY on linux to avoid latency issues
Signed-off-by: Francis Bouvier <[email protected]>
1 parent 0813d99 commit c3a3ac1

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

src/main.zig

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
const std = @import("std");
2020
const posix = std.posix;
21+
const builtin = @import("builtin");
2122

2223
const jsruntime = @import("jsruntime");
2324

@@ -99,6 +100,10 @@ pub const StreamServer = struct {
99100
self.* = undefined;
100101
}
101102

103+
fn setSockOpt(fd: posix.socket_t, level: i32, option: u32, value: c_int) !void {
104+
try posix.setsockopt(fd, level, option, &std.mem.toBytes(value));
105+
}
106+
102107
pub fn listen(self: *StreamServer, address: std.net.Address) !void {
103108
const sock_flags = posix.SOCK.STREAM | posix.SOCK.CLOEXEC;
104109
var use_sock_flags: u32 = sock_flags;
@@ -112,21 +117,16 @@ pub const StreamServer = struct {
112117
self.sockfd = null;
113118
}
114119

120+
// socket options
115121
if (self.reuse_address) {
116-
try posix.setsockopt(
117-
sockfd,
118-
posix.SOL.SOCKET,
119-
posix.SO.REUSEADDR,
120-
&std.mem.toBytes(@as(c_int, 1)),
121-
);
122+
try setSockOpt(sockfd, posix.SOL.SOCKET, posix.SO.REUSEADDR, 1);
122123
}
123124
if (@hasDecl(posix.SO, "REUSEPORT") and self.reuse_port) {
124-
try posix.setsockopt(
125-
sockfd,
126-
posix.SOL.SOCKET,
127-
posix.SO.REUSEPORT,
128-
&std.mem.toBytes(@as(c_int, 1)),
129-
);
125+
try setSockOpt(sockfd, posix.SOL.SOCKET, posix.SO.REUSEPORT, 1);
126+
}
127+
if (builtin.target.os.tag == .linux) { // posix.TCP not available on MacOS
128+
// WARNING: disable Nagle's alogrithm to avoid latency issues
129+
try setSockOpt(sockfd, posix.IPPROTO.TCP, posix.TCP.NODELAY, 1);
130130
}
131131

132132
var socklen = address.getOsSockLen();

0 commit comments

Comments
 (0)