Sending Messages
NATS sends and receives messages using a protocol that includes a target subject, an optional reply subject and an array of bytes. Some libraries may provide helpers to convert other data formats to and from bytes, but the NATS server will treat all messages as opaque byte arrays.
All of the NATS clients are designed to make sending a message simple. For example, to send the string “All is Well” to the “updates” subject as a UTF-8 string of bytes you would do:
Go
Java
JavaScript
Python
Ruby
1
nc, err := nats.Connect("demo.nats.io", nats.Name("API PublishBytes Example"))
2
if err != nil {
3
log.Fatal(err)
4
}
5
defer nc.Close()
6
7
if err := nc.Publish("updates", []byte("All is Well")); err != nil {
8
log.Fatal(err)
9
}
Copied!
1
Connection nc = Nats.connect("nats://demo.nats.io:4222");
2
3
nc.publish("updates", "All is Well".getBytes(StandardCharsets.UTF_8));
4
5
// Make sure the message goes through before we close
6
nc.flush(Duration.ZERO);
7
nc.close();
Copied!
1
const sc = StringCodec();
2
nc.publish("updates", sc.encode("All is Well"));
Copied!
1
nc = NATS()
2
3
await nc.connect(servers=["nats://demo.nats.io:4222"])
4
5
await nc.publish("updates", b'All is Well')
Copied!
1
require 'nats/client'
2
3
NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc|
4
nc.publish("updates", "All is Well")
5
end
Copied!
Last modified 21d ago
Export as PDF
Copy link
Edit on GitHub