Connecting to the Default Server

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

{% tabs %} {% tab title=”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

{% endtab %}

{% tab title=”Java” %}

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

{% endtab %}

{% tab title=”JavaScript” %}

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

{% endtab %}

{% tab title=”Python” %}

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

{% endtab %}

{% tab title=”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

{% endtab %}

{% tab title=”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);

{% endtab %} {% endtabs %}