Ping/Pong Protocol
The client and server use a simple PING/PONG protocol to check that either of them are still connected to the other. On a regular interval the client will ping the server, which responds with a pong.
Once a configurable maximum of outstanding pings without a single pong reply is hit, the connection is closed as stale. Together these two values define a timeout for the connection which specifies how quickly the client will be notified of a problem. This will also help when there is a remote network partition where the operating system does not detect a socket error. Upon connection close, the client will attempt to reconnect. When it knows about other servers, these will be tried next.
In the presence of traffic, such as messages or client side pings, the server will not initiate the PING/PONG interaction.
On connections with a lot of traffic, the client will often figure out there is a problem between PINGS, and as a result the default PING interval is often on the order of minutes. To set the interval to 20s and limit outstanding pings to 5, thus forcing a closed connection after 100s of inactivity:
Go
Java
JavaScript
Python
Ruby
C
1
// Set Ping Interval to 20 seconds
2
nc, err := nats.Connect("demo.nats.io", nats.Name("API Ping Example"), nats.PingInterval(20*time.Second), nats.MaxPingsOutstanding(5))
3
if err != nil {
4
log.Fatal(err)
5
}
6
defer nc.Close()
7
8
// Do something with the connection
Copied!
1
Options options = new Options.Builder().
2
server("nats://demo.nats.io:4222").
3
pingInterval(Duration.ofSeconds(20)). // Set Ping Interval
4
maxPingsOut(5). // Set max pings in flight
5
build();
6
Connection nc = Nats.connect(options);
7
8
// Do something with the connection
9
10
nc.close();
Copied!
1
const nc = await connect({
2
pingInterval: 20 * 1000,
3
servers: ["demo.nats.io:4222"],
4
});
Copied!
1
nc = NATS()
2
3
await nc.connect(
4
servers=["nats://demo.nats.io:4222"],
5
# Set Ping Interval to 20 seconds
6
ping_interval=20,
7
max_outstanding_pings=5,
8
)
9
10
# Do something with the connection.
Copied!
1
require 'nats/client'
2
3
NATS.start(ping_interval: 20, max_outstanding_pings: 5) do |nc|
4
nc.on_reconnect do
5
puts "Got reconnected to #{nc.connected_server}"
6
end
7
8
nc.on_disconnect do |reason|
9
puts "Got disconnected! #{reason}"
10
end
11
12
# Do something with the connection
13
end
Copied!
1
natsConnection *conn = NULL;
2
natsOptions *opts = NULL;
3
natsStatus s = NATS_OK;
4
5
s = natsOptions_Create(&opts);
6
if (s == NATS_OK)
7
// Set Ping interval to 20 seconds (20,000 milliseconds)
8
s = natsOptions_SetPingInterval(opts, 20000);
9
if (s == NATS_OK)
10
// Set the limit to 5
11
s = natsOptions_SetMaxPingsOut(opts, 5);
12
if (s == NATS_OK)
13
s = natsConnection_Connect(&conn, opts);
14
15
(...)
16
17
// Destroy objects that were created
18
natsConnection_Destroy(conn);
19
natsOptions_Destroy(opts);
Copied!
Last modified 10d ago
Export as PDF
Copy link
Edit on GitHub