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. let nc = NATS.connect("nats://demo.nats.io:4222");
  2. // on node you *must* register an error listener. If not registered
  3. // the library emits an 'error' event, the node process will exit.
  4. nc.on('error', (err) => {
  5. t.log('client got an error:', err);
  6. });
  7. if(nc.closed) {
  8. t.log('client is closed');
  9. } else {
  10. t.log('client is not closed');
  11. }

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

TypeScript

  1. if(nc.isClosed()) {
  2. t.log('the client is closed');
  3. } else {
  4. t.log('the client is running');
  5. }