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

nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
    log.Fatal(err)
}
defer nc.Close()

// Do something with the connection

Java

Connection nc = Nats.connect();

// Do something with the connection

nc.close();

JavaScript

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

Python

nc = NATS()
await nc.connect()

# Do something with the connection

await nc.close()

C#

// dotnet add package NATS.Net
using NATS.Net;

await using var client = new NatsClient();

// It's optional to call ConnectAsync()
// as it will be called when needed automatically
await client.ConnectAsync();

Ruby

require 'nats/client'

NATS.start do |nc|
   # Do something with the connection

   # Close the connection
   nc.close
end

C

natsConnection      *conn = NULL;
natsStatus          s;

s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);
if (s != NATS_OK)
  // handle error

// Destroy connection, no-op if conn is NULL.
natsConnection_Destroy(conn);

版本号 #1
由 cocobook-sync 创建于 2026-10-28 11:11:03 UTC
由 cocobook-sync 更新于 2026-10-28 11:11:03 UTC