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:

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");

Java

  1. Connection nc = Nats.connect("nats://demo.nats.io:4222");
  2. // Do something with the connection
  3. nc.close();

JavaScript

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

Python

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

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

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);

{% endtabs %}