Connecting to a Specific Server

The NATS client libraries can take a full URL, nats://demo.nats.io:4222, to specify a specific server host and port to connect to.

Libraries are removing the requirement for an explicit protocol and may allow demo.nats.io:4222 or just demo.nats.io. In the later example the default port 4222 will be used. Check with your specific client library’s documentation to see what URL formats are supported.

For example, to connect to the demo server with a URL you can use:

{% tabs %} {% tab title=”Go” %}

  1. // If connecting to the default port, the URL can be simplified
  2. // to just the hostname/IP.
  3. // That is, the connect below is equivalent to:
  4. // nats.Connect("nats://demo.nats.io:4222")
  5. nc, err := nats.Connect("demo.nats.io")
  6. if err != nil {
  7. log.Fatal(err)
  8. }
  9. defer nc.Close()
  10. // Do something with the connection nc = Nats.connect("nats://demo.nats.io:4222");

{% endtab %}

{% tab title=”Java” %}

  1. // Connection is AutoCloseable
  2. try (Connection nc = Nats.connect("nats://demo.nats.io:4222")) {
  3. // Do something with the connection
  4. }

{% endtab %}

{% tab title=”JavaScript” %}

  1. const nc = await connect({ servers: "demo.nats.io" });
  2. // Do something with the connection
  3. doSomething();
  4. await nc.close();

{% endtab %}

{% tab title=”Python” %}

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

{% endtab %}

{% tab title=”C# v1” %}

  1. // IConnection is IDisposable
  2. using (IConnection c = new ConnectionFactory().CreateConnection("nats://demo.nats.io:4222"))
  3. {
  4. // Do something with the connection
  5. }

{% endtab %}

{% tab title=”C# v2” %}

  1. // NATS server URL is part of the connection options
  2. var opts = new NatsOpts { Url = "nats://demo.nats.io:4222" };
  3. // NatsConnection is IAsyncDisposable
  4. await using var nats = new NatsConnection(opts);
  5. // Do something with the connection

{% endtab %}

{% tab title=”Ruby” %}

  1. require 'nats/client'
  2. NATS.start(servers: ["nats://demo.nats.io:4222"]) 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. // If connecting to the default port, the URL can be simplified
  4. // to just the hostname/IP.
  5. // That is, the connect below is equivalent to:
  6. // natsConnection_ConnectTo(&conn, "nats://demo.nats.io:4222");
  7. s = natsConnection_ConnectTo(&conn, "demo.nats.io");
  8. if (s != NATS_OK)
  9. // handle error
  10. // Destroy connection, no-op if conn is NULL.
  11. natsConnection_Destroy(conn);

{% endtab %}

{% endtabs %}