Connecting to the Default Server

Some libraries also provide a special way to connect to a default url, which is generally nats://localhost:4222:

Go

  1. nc, err := nats.Connect(nats.DefaultURL)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. defer nc.Close()
  6. // Do something with the connection

Java

  1. Connection nc = Nats.connect();
  2. // Do something with the connection
  3. nc.close();

JavaScript

  1. const nc = await connect();
  2. // Do something with the connection
  3. doSomething();
  4. // When done close it
  5. await nc.close();

Python

  1. nc = NATS()
  2. await nc.connect()
  3. # Do something with the connection
  4. await nc.close()

Ruby

  1. require 'nats/client'
  2. NATS.start do |nc|
  3. # Do something with the connection
  4. # Close the connection
  5. nc.close
  6. end

C

  1. natsConnection *conn = NULL;
  2. natsStatus s;
  3. s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);
  4. if (s != NATS_OK)
  5. // handle error
  6. // Destroy connection, no-op if conn is NULL.
  7. natsConnection_Destroy(conn);

{% endtabs %}