Setting a Connect Timeout

Each library has its own, language preferred way, to pass connection options. One of the most common options is a connect timeout. It limits how long it can take to establish a connection to a server. Should multiple URLs be provided, this timeout applies to each cluster member individually. To set the maximum time to connect to a server to 10 seconds:

Go

  1. nc, err := nats.Connect("demo.nats.io", nats.Name("API Options Example"), nats.Timeout(10*time.Second))
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. defer nc.Close()
  6. // Do something with the connection

Java

  1. Options options = new Options.Builder().
  2. server("nats://demo.nats.io:4222").
  3. connectionTimeout(Duration.ofSeconds(10)). // Set timeout
  4. build();
  5. Connection nc = Nats.connect(options);
  6. // Do something with the connection
  7. nc.close();

JavaScript

  1. let nc = NATS.connect({
  2. url: "nats://demo.nats.io:4222",
  3. timeout: 10*1000 //10s
  4. });
  5. nc.on('connect', (c) => {
  6. // Do something with the connection
  7. doSomething();
  8. // When done close it
  9. nc.close();
  10. });
  11. nc.on('error', (err) => {
  12. failed(err);
  13. });

Python

  1. nc = NATS()
  2. await nc.connect(
  3. servers=["nats://demo.nats.io:4222"],
  4. connect_timeout=10)
  5. # Do something with the connection
  6. await nc.close()

Ruby

  1. # There is currently no connect timeout as part of the Ruby NATS client API, but you can use a timer to mimic it.
  2. require 'nats/client'
  3. timer = EM.add_timer(10) do
  4. NATS.connect do |nc|
  5. # Do something with the connection
  6. # Close the connection
  7. nc.close
  8. end
  9. end
  10. EM.cancel_timer(timer)

TypeScript

  1. let nc = await connect({
  2. url: "nats://demo.nats.io:4222",
  3. timeout: 10*1000 //10s
  4. });

C

  1. nnatsConnection *conn = NULL;
  2. natsOptions *opts = NULL;
  3. natsStatus s = NATS_OK;
  4. s = natsOptions_Create(&opts);
  5. if (s == NATS_OK)
  6. // Set the timeout to 10 seconds (10,000 milliseconds)
  7. s = natsOptions_SetTimeout(opts, 10000);
  8. if (s == NATS_OK)
  9. s = natsConnection_Connect(&conn, opts);
  10. (...)
  11. // Destroy objects that were created
  12. natsConnection_Destroy(conn);
  13. natsOptions_Destroy(opts);