Powered By GitBook
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
Java
JavaScript
Python
Ruby
TypeScript
C
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
11
// Do something with the connection nc = Nats.connect("nats://demo.nats.io:4222");
Copied!
1
Connection nc = Nats.connect("nats://demo.nats.io:4222");
2
3
// Do something with the connection
4
5
nc.close();
Copied!
1
let nc = NATS.connect("nats://demo.nats.io:4222");
2
nc.on('connect', (c) => {
3
// Do something with the connection
4
doSomething();
5
// When done close it
6
nc.close();
7
});
8
nc.on('error', (err) => {
9
failed(err);
10
});
Copied!
1
nc = NATS()
2
await nc.connect(servers=["nats://demo.nats.io:4222"])
3
4
# Do something with the connection
5
6
await nc.close()
Copied!
1
require 'nats/client'
2
3
NATS.start(servers: ["nats://demo.nats.io:4222"]) do |nc|
4
# Do something with the connection
5
6
# Close the connection
7
nc.close
8
end
Copied!
1
// will throw an exception if connection fails
2
let nc = await connect("nats://demo.nats.io:4222");
3
// Do something with the connection
4
5
// Close the connection
6
nc.close();
Copied!
1
natsConnection *conn = NULL;
2
natsStatus s;
3
4
// If connecting to the default port, the URL can be simplified
5
// to just the hostname/IP.
6
// That is, the connect below is equivalent to:
7
// natsConnection_ConnectTo(&conn, "nats://demo.nats.io:4222");
8
s = natsConnection_ConnectTo(&conn, "demo.nats.io");
9
if (s != NATS_OK)
10
// handle error
11
12
// Destroy connection, no-op if conn is NULL.
13
natsConnection_Destroy(conn);
Copied!
Last modified 1yr ago
Export as PDF
Copy link