Monitoring the Connection

Managing the interaction with the server is primarily the job of the client library but most of the libraries also provide some insight into what is happening under the covers.

For example, the client library may provide a mechanism to get the connection’s current status:

Go

  1. nc, err := nats.Connect("demo.nats.io", nats.Name("API Example"))
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. defer nc.Close()
  6. getStatusTxt := func(nc *nats.Conn) string {
  7. switch nc.Status() {
  8. case nats.CONNECTED:
  9. return "Connected"
  10. case nats.CLOSED:
  11. return "Closed"
  12. default:
  13. return "Other"
  14. }
  15. }
  16. log.Printf("The connection is %v\n", getStatusTxt(nc))
  17. nc.Close()
  18. log.Printf("The connection is %v\n", getStatusTxt(nc))

Java

  1. Connection nc = Nats.connect("nats://demo.nats.io:4222");
  2. System.out.println("The Connection is: " + nc.getStatus());
  3. nc.close();
  4. System.out.println("The Connection is: " + nc.getStatus());

JavaScript

  1. // you can find out where you connected:
  2. t.log(`connected to a nats server version ${nc.info.version}`);
  3. // or information about the data in/out of the client:
  4. const stats = nc.stats();
  5. t.log(`client sent ${stats.outMsgs} messages and received ${stats.inMsgs}`);

Python

  1. nc = NATS()
  2. await nc.connect(
  3. servers=["nats://demo.nats.io:4222"],
  4. )
  5. # Do something with the connection.
  6. print("The connection is connected?", nc.is_connected)
  7. while True:
  8. if nc.is_reconnecting:
  9. print("Reconnecting to NATS...")
  10. break
  11. await asyncio.sleep(1)
  12. await nc.close()
  13. print("The connection is closed?", nc.is_closed)

Ruby

  1. NATS.start(max_reconnect_attempts: 2) do |nc|
  2. puts "Connect is connected?: #{nc.connected?}"
  3. timer = EM.add_periodic_timer(1) do
  4. if nc.closing?
  5. puts "Connection closed..."
  6. EM.cancel_timer(timer)
  7. NATS.stop
  8. end
  9. if nc.reconnecting?
  10. puts "Reconnecting to NATS..."
  11. next
  12. end
  13. end
  14. end

{% endtabs %}