The virtues of the NATS protocol manifest quickly when you experience how easy it is to use NATS. Because the NATS protocol is text-based, you can use NATS across virtually any platform or language.
In the following demo we use Telnet. On the wire you can publish and subscribe using a simple set of protocol commands.
Open a terminal and initiate a connection to the NATS demo instance.
telnet demo.nats.io 4222
The expected result will roughly look like this. Note the IP address, and
INFOpayload may have different values.
Connected to demo.nats.io.
Escape character is '^]'.
Any client establishing a connection with the server must send
CONNECTmessage to confirm the connection. There are several options that can be specified to indicate the client supported features, but for the purpose of this example, we can send an empty payload.
You will see a
+OKmessage in response.
Not long after the
CONNECTyou will see a
PINGmessage. There is a bi-directional behavior between the client and server to check for liveness. In the case of the server, after some period of time without a
PONG, the server will shutdown the client connection. If the client does not hear back a
PONG, it will attempt to reconnect to a different server in a clustered setup, if available.
You can respond to the server, but simply typing
PONGfollowed by a return.
Subscribe to the wildcard subject
foo.*with subscription ID of
SUB foo.* 90
+OKmessage will follow, indicating a successful subscription.
NATS connection are bi-directional, so we can not only subscribe to subjects, but we can publish to them as well.
We can send the
PUBcommand followed by the subject, and the length of the message payload that will be followed on the second line. In this case,
hellois the payload. Once that is typed, hit return which will send the message.
PUB foo.bar 5
+OKmessage will follow, indicating a successful publish.
Immediately following, a
MSGmessage will appear which indicates the subscription received the message that was just published.
MSG foo.bar 90 5
You can use the
UNSUBcommand to unsubscribe from a message.
Run the subscriber to unsubscribe:
Now that we unsubscribed, if we attempt to publish again, we will receive the
+OK, but will not receive a
PUB foo.bar 7
ctrl+cto close the connection, however, as noted above, if this is not done, after some period of inactivity the server will automatically close the connection.