NATS文档
  • 欢迎
  • 发行备注
    • 最新情况
      • NATS 2.2
      • NATS 2.0
  • NATS 概念
    • 概览
      • 比较 NATS
    • 什么是NATS
      • 演练安装
    • 基于主题的消息
    • 核心NATS
      • 发布和订阅
        • 发布/订阅演 练
      • 请求和响应
        • 请求/响应 演练
      • 队列组
        • 队列 演练
    • JetStream
      • 流
      • 消费者
        • 示例
      • JetStream 演练
      • 键值对存储
        • 键值对存储演练
      • 对象存储
        • 对象存储演练
    • 主题映射与分区
    • NATS服务器基础架构
      • NATS部署架构适配
    • 安全
    • 连接性
  • 使用 NATS
    • NATS工具
      • nats
        • nats基准测试
      • nk
      • nsc
        • 基础
        • 流
        • 服务
        • 签名密钥
        • 撤销
        • 管理操作
      • nats-top
        • 教程
    • 用NATS开发
      • 一个NATS应用的解剖
      • 连接
        • 连接到默认服务器
        • 连接到特定服务器
        • 连接到群集
        • 连接名称
        • 用用户名和密码做认证
        • 用令牌做认证
        • 用NKey做认证
        • 用一个可信文件做认证
        • 用TLS加密连接
        • 设置连接超时
        • 乒乓协议
        • 关闭响应消息
        • 杂技功能
        • 自动恢复
          • 禁用自动重连
          • 设置自动重新连接的最大次数
          • 随机
          • 重连尝试之间暂停
          • 关注重连事件
          • 重连尝试期间缓存消息
        • 监视连接
          • 关注连接事件
          • 低速消费者
      • 接收消息
        • 同步订阅
        • 异步订阅
        • 取消订阅
        • N个消息后取消订阅
        • 回复一个消息
        • 通配符订阅
        • 队列订阅
        • 断开连接前清除消息
        • 接收结构化数据
      • 发送消息
        • 包含一个回复主题
        • 请求回复语义
        • 缓存刷入和乒
        • 发送结构化数据
      • JetStream
        • 深入JetStream模型
        • 管理流和消费者
        • 消费者详情
        • 发布到流
        • 使用键值对存储
        • 使用对象存储
      • 教程
        • 用go做个自定义拨号器
  • 运行一个NATS服务
    • 安装、运行和部署NATS服务
      • 安装一个NATS服务
      • 运行和部署一个NATS服务
      • Windows服务
      • 信号
    • 环境约束
    • NATS和Docker
      • 教程
      • Docker Swarm
      • Python 和 NGS 运行在Docker
      • JetStream
    • NATS和Kubernetes
      • 用Helm 部署NATS
      • 创建一个Kubernetes群集
      • NATS群集和认证管理
      • 用cfssl保护NATS群集
      • 用负载均衡来保护外部的NATS访问
      • 在Digital Ocean用Helm创建超级NATS群集
      • 使用Helm从0到K8S再到叶子节点
    • NATS服务的客户端
    • 配置 NATS服务
      • 配置 JetStream
        • 配置管理 Management
          • NATS管理命令行
          • 地形
          • GitHub Actions
          • Kubernetes控制器
      • 群集
        • 群集配置
        • JetStream 群集
          • 管理
      • 网关超级群集
        • 配置
      • 叶子节点
        • 配置
        • JetStream在叶子节点
      • 安全加固NATS
        • 使用 TLS
        • 认证
          • 令牌
          • 用户名/密码
          • TLS认证
            • 群集中的TLS认证
          • NKeys
          • 认证超时
          • 去中心化的 JWT 认证/授权
            • 使用解析器查找帐户
            • 内存解析器教程
            • 混合认证/授权安装
        • 授权
        • 基于账户的多租户
        • OCSP Stapling
      • 日志
      • 使用监控
      • MQTT
        • 配置
      • 配置主题映射
      • 系统事件
        • 系统时间和去中心化的JWT教程
      • WebSocket
        • 配置
    • 管理和监控你的NATS服务基础架构
      • 监控
        • 监控 JetStream
      • 管理 JetStream
        • 账号信息
        • 命名流,消费者和账号
        • 流
        • 消费者
        • 数据复制
        • 灾难回复
        • 加密Rest
      • 管理JWT安全
        • 深入JWT指南
      • 升级一个群集
      • 慢消费者
      • 信号
      • 跛脚鸭模式
  • 参考
    • 常见问题
    • NATS协议
      • 协议演示
      • 客户端协议
        • 开发一个客户端
      • NATS群集协议
      • JetStream API参考
  • 遗产
    • STAN='NATS流'
      • STAN概念
        • 和NATS的关系
        • 客户端连接
        • 频道
          • 消息日志
          • 订阅
            • 通常的
            • 持久化的
            • 队列组
            • 重新投递
        • 存储接口
        • 存储加密
        • 群集
          • Supported Stores
          • Configuration
          • Auto Configuration
          • Containers
        • Fault Tolerance
          • Active Server
          • Standby Servers
          • Shared State
          • Failover
        • Partitioning
        • Monitoring
          • Endpoints
      • Developing With STAN
        • Connecting to NATS Streaming Server
        • Publishing to a Channel
        • Receiving Messages from a Channel
        • Durable Subscriptions
        • Queue Subscriptions
        • Acknowledgements
        • The Streaming Protocol
      • STAN NATS Streaming Server
        • Installing
        • Running
        • Configuring
          • Command Line Arguments
          • Configuration File
          • Store Limits
          • Persistence
            • File Store
            • SQL Store
          • Securing
        • Process Signaling
        • Windows Service
        • Embedding NATS Streaming Server
        • Docker Swarm
        • Kubernetes
          • NATS Streaming with Fault Tolerance.
    • nats账号服务
      • Basics
      • Inspecting JWTs
      • Directory Store
      • Update Notifications
由 GitBook 提供支持
在本页
  • Client Protocol
  • Protocol conventions
  • Protocol messages
  • INFO
  • Description
  • Syntax
  • Example
  • CONNECT
  • Description
  • Syntax
  • Example
  • PUB
  • Description
  • Syntax
  • Example
  • HPUB
  • Description
  • Syntax
  • Example
  • SUB
  • Description
  • Syntax
  • Example
  • UNSUB
  • Description
  • Syntax
  • Example
  • MSG
  • Description
  • Syntax
  • Example
  • HMSG
  • Description
  • Syntax
  • Example
  • PING/PONG
  • Description
  • Syntax
  • Example
  • +OK/ERR
  • Description
  • Syntax
  1. 参考
  2. NATS协议

客户端协议

上一页协议演示下一页开发一个客户端

最后更新于2年前

Client Protocol

The wire protocol used to communicate between the NATS server and clients is a simple, text-based publish/subscribe style protocol. Clients connect to and communicate with nats-server (the NATS server) through a regular TCP/IP socket using a small set of protocol operations that are terminated by a new line.

Unlike traditional messaging systems that use a binary message format that require an API to consume, the text-based NATS protocol makes it easy to implement clients in a wide variety of programming and scripting languages. In fact, refer to the topic to play with the NATS protocol for yourself using telnet.

The NATS server implements a that is fast and efficient.

Protocol conventions

Control Line with Optional Content: Each interaction between the client and server consists of a control, or protocol, line of text followed, optionally by message content. Most of the protocol messages don't require content, only PUB, MSG, HPUB, and HMSG include payloads.

Field Delimiters: The fields of NATS protocol messages are delimited by whitespace characters (space) or (tab). Multiple whitespace characters will be treated as a single field delimiter.

Newlines: NATS uses ␍ followed by ␊ (␍␊, 0x0D0A) to terminate protocol messages. This newline sequence is also used to mark the end of the message payload in PUB, MSG, HPUB, and HMSG protocol messages.

Subject names: Subject names, including reply subject names, are case-sensitive and must be non-empty alphanumeric strings with no embedded whitespace. All ascii alphanumeric characters except spaces/tabs and separators which are . and > are allowed. Subject names can be optionally token-delimited using the dot character (.), e.g.:

FOO, BAR, foo.bar, foo.BAR, FOO.BAR and FOO.BAR.BAZ are all valid subject names

FOO. BAR, foo. .bar andfoo..bar are not valid subject names

A subject is comprised of 1 or more tokens. Tokens are separated by . and can be any non space ascii alphanumeric character. The full wildcard token > is only valid as the last token and matches all tokens past that point. A token wildcard, * matches any token in the position it was listed. Wildcard tokens should only be used in a wildcard capacity and not part of a literal token.

Character Encoding: Subject names should be ascii characters for maximum interoperability. Due to language constraints and performance, some clients may support UTF-8 subject names, as may the server. No guarantees of non-ASCII support are provided.

Wildcards: NATS supports the use of wildcards in subject subscriptions.

  • The asterisk character (*) matches a single token at any level of the subject.

  • The greater than symbol (>), also known as the full wildcard, matches one or more tokens at the tail of a subject, and must be the last token. The wildcarded subject foo.> will match foo.bar or foo.bar.baz.1, but not foo.

  • Wildcards must be a separate token (foo.*.baz or foo.> are syntactically valid; foo*.bar, f*o.b*r and foo> are not)

For example, the wildcard subscriptions foo.*.quux and foo.> both match foo.bar.quux, but only the latter matches foo.bar.baz. With the full wildcard, it is also possible to express interest in every subject that may exist in NATS: sub > 1, limited of course by authorization settings.

Protocol messages

The following table briefly describes the NATS protocol messages. NATS protocol operation names are case insensitive, thus SUB foo 1␍␊ and sub foo 1␍␊ are equivalent.

Click the name to see more detailed information, including syntax:

OP Name
Sent By
Description

Server

Sent to client after initial TCP/IP connection

Client

Sent to server to specify connection information

Client

Publish a message to a subject, with optional reply subject

Client

Publish a message to a subject including NATS headers, with optional reply subject

Client

Subscribe to a subject (or subject wildcard)

Client

Unsubscribe (or auto-unsubscribe) from subject

Server

Delivers a message payload to a subscriber

Server

Delivers a message payload to a subscriber with NATS headers

Both

PING keep-alive message

Both

PONG keep-alive response

Server

Acknowledges well-formed protocol message in verbose mode

Server

Indicates a protocol error. May cause client disconnect.

The following sections explain each protocol message.

INFO

Description

A client will need to start as a plain TCP connection, then when the server accepts a connection from the client, it will send information about itself, the configuration and security requirements necessary for the client to successfully authenticate with the server and exchange messages.

Syntax

INFO {["option_name":option_value],...}␍␊

The valid options are as follows:

  • server_id: The unique identifier of the NATS server

  • version: The version of the NATS server

  • go: The version of golang the NATS server was built with

  • host: The IP address used to start the NATS server, by default this will be 0.0.0.0 and can be configured with -client_advertise host:port

  • port: The port number the NATS server is configured to listen on

  • max_payload: Maximum payload size, in bytes, that the server will accept from the client.

  • proto: An integer indicating the protocol version of the server. The server version 1.2.0 sets this to 1 to indicate that it supports the "Echo" feature.

  • client_id: An optional unsigned integer (64 bits) representing the internal client identifier in the server. This can be used to filter client connections in monitoring, correlate with error logs, etc...

  • auth_required: If this is set, then the client should try to authenticate upon connect.

  • tls_required: If this is set, then the client must perform the TLS/1.2 handshake. Note, this used to be ssl_required and has been updated along with the protocol from SSL to TLS.

  • tls_verify: If this is set, the client must provide a valid certificate during the TLS handshake.

  • connect_urls : An optional list of server urls that a client can connect to.

  • ldm: If the server supports Lame Duck Mode notifications, and the current server has transitioned to lame duck, ldm will be set to true.

connect_urls

The connect_urls field is a list of urls the server may send when a client first connects, and when there are changes to server cluster topology. This field is considered optional, and may be omitted based on server configuration and client protocol level.

When a NATS server cluster expands, an INFO message is sent to the client with an updated connect_urls list. This cloud-friendly feature asynchronously notifies a client of known servers, allowing it to connect to servers not originally configured.

The connect_urls will contain a list of strings with an IP and port, looking like this: "connect_urls":["10.0.0.184:4333","192.168.129.1:4333","192.168.192.1:4333"]

Example

Below you can see a sample connection string from a telnet connection to the demo.nats.io site.

telnet demo.nats.io 4222
Trying 107.170.221.32...
Connected to demo.nats.io.
Escape character is '^]'.
INFO {"server_id":"Zk0GQ3JBSrg3oyxCRRlE09","version":"1.2.0","proto":1,"go":"go1.10.3","host":"0.0.0.0","port":4222,"max_payload":1048576,"client_id":2392}

CONNECT

Description

Syntax

CONNECT {["option_name":option_value],...}␍␊

The valid options are as follows:

  • pedantic: Turns on additional strict format checking, e.g. for properly formed subjects

  • tls_required: Indicates whether the client requires an SSL connection.

  • auth_token: Client authorization token (if auth_required is set)

  • user: Connection username (if auth_required is set)

  • pass: Connection password (if auth_required is set)

  • name: Optional client name

  • lang: The implementation language of the client.

  • version: The version of the client.

  • echo: Optional boolean. If set to true, the server (version 1.2.0+) will not send originating messages from this connection to its own subscriptions. Clients should set this to true only for server supporting this feature, which is when proto in the INFO protocol is set to at least 1.

  • sig: In case the server has responded with a nonce on INFO, then a NATS client must use this field to reply with the signed nonce.

  • jwt: The JWT that identifies a user permissions and account.

Example

Here is an example from the default string of the Go client:

CONNECT {"verbose":false,"pedantic":false,"tls_required":false,"name":"","lang":"go","version":"1.2.2","protocol":1}␍␊

PUB

Description

The PUB message publishes the message payload to the given subject name, optionally supplying a reply subject. If a reply subject is supplied, it will be delivered to eligible subscribers along with the supplied payload. Note that the payload itself is optional. To omit the payload, set the payload size to 0, but the second CRLF is still required.

Syntax

PUB <subject> [reply-to] <#bytes>␍␊[payload]␍␊

where:

  • subject: The destination subject to publish to

  • reply-to: The optional reply subject that subscribers can use to send a response back to the publisher/requestor

  • #bytes: The payload size in bytes

  • payload: The message payload data

Example

To publish the ASCII string message payload "Hello NATS!" to subject FOO:

PUB FOO 11␍␊Hello NATS!␍␊

To publish a request message "Knock Knock" to subject FRONT.DOOR with reply subject JOKE.22:

PUB FRONT.DOOR JOKE.22 11␍␊Knock Knock␍␊

To publish an empty message to subject NOTIFY:

PUB NOTIFY 0␍␊␍␊

HPUB

Description

The HPUB message is the same as PUB but extends the message payload to include NATS headers. Note that the payload itself is optional. To omit the payload, set the total message size equal to the size of the headers. Note that the trailing CR+LF is still required.

Syntax

HPUB <subject> [reply-to] <#header bytes> <#total bytes>␍␊[headers]␍␊␍␊[payload]␍␊

where:

  • subject: The destination subject to publish to

  • reply-to: The optional reply subject that subscribers can use to send a response back to the publisher/requestor

  • #header bytes: The size of the headers section in bytes including the ␍␊␍␊ delimiter before the payload

  • #total bytes: The total size of headers and payload sections in bytes

  • headers: Header version NATS/1.0␍␊ followed by one or more name: value pairs, each separated by ␍␊

  • payload: The message payload data

Example

To publish the ASCII string message payload "Hello NATS!" to subject FOO with one header Bar with value Baz:

HPUB FOO 22 33␍␊NATS/1.0␍␊Bar: Baz␍␊␍␊Hello NATS!␍␊

To publish a request message "Knock Knock" to subject FRONT.DOOR with reply subject JOKE.22 and two headers:

HPUB FRONT.DOOR JOKE.22 45 56␍␊NATS/1.0␍␊BREAKFAST: donut␍␊LUNCH: burger␍␊␍␊Knock Knock␍␊

To publish an empty message to subject NOTIFY with one header Bar with value Baz:

HPUB NOTIFY 22 22␍␊NATS/1.0␍␊Bar: Baz␍␊␍␊␍␊

To publish a message to subject MORNING MENU with one header BREAKFAST having two values and payload "Yum!"

HPUB MORNING.MENU 47 51␍␊NATS/1.0␍␊BREAKFAST: donut␍␊BREAKFAST: eggs␍␊␍␊Yum!␍␊

SUB

Description

SUB initiates a subscription to a subject, optionally joining a distributed queue group.

Syntax

SUB <subject> [queue group] <sid>␍␊

where:

  • subject: The subject name to subscribe to

  • queue group: If specified, the subscriber will join this queue group

  • sid: A unique alphanumeric subscription ID, generated by the client

Example

To subscribe to the subject FOO with the connection-unique subscription identifier (sid) 1:

SUB FOO 1␍␊

To subscribe the current connection to the subject BAR as part of distribution queue group G1 with sid 44:

SUB BAR G1 44␍␊

UNSUB

Description

UNSUB unsubscribes the connection from the specified subject, or auto-unsubscribes after the specified number of messages has been received.

Syntax

UNSUB <sid> [max_msgs]␍␊

where:

  • sid: The unique alphanumeric subscription ID of the subject to unsubscribe from

  • max_msgs: An optional number of messages to wait for before automatically unsubscribing

Example

The following examples concern subject FOO which has been assigned sid 1. To unsubscribe from FOO:

UNSUB 1␍␊

To auto-unsubscribe from FOO after 5 messages have been received:

UNSUB 1 5␍␊

MSG

Description

The MSG protocol message is used to deliver an application message to the client.

Syntax

MSG <subject> <sid> [reply-to] <#bytes>␍␊[payload]␍␊

where:

  • subject: Subject name this message was received on

  • sid: The unique alphanumeric subscription ID of the subject

  • reply-to: The subject on which the publisher is listening for responses

  • #bytes: Size of the payload in bytes

  • payload: The message payload data

Example

The following message delivers an application message from subject FOO.BAR:

MSG FOO.BAR 9 11␍␊Hello World␍␊

To deliver the same message along with a reply subject:

MSG FOO.BAR 9 GREETING.34 11␍␊Hello World␍␊

HMSG

Description

Syntax

HMSG <subject> <sid> [reply-to] <#header bytes> <#total bytes>␍␊[payload]␍␊

where:

  • subject: Subject name this message was received on

  • sid: The unique alphanumeric subscription ID of the subject

  • reply-to: The subject on which the publisher is listening for responses

  • #header bytes: The size of the headers section in bytes including the ␍␊␍␊ delimiter before the payload

  • #total bytes: The total size of headers and payload sections in bytes

  • headers: Header version NATS/1.0␍␊ followed by one or more name: value pairs, each separated by ␍␊

  • payload: The message payload data

Example

The following message delivers an application message from subject FOO.BAR with a header:

HMSG FOO.BAR 34 45␍␊NATS/1.0␍␊FoodGroup: vegetable␍␊␍␊Hello World␍␊

To deliver the same message along with a reply subject:

HMSG FOO.BAR 9 BAZ.69 34 45␍␊NATS/1.0␍␊FoodGroup: vegetable␍␊␍␊Hello World␍␊

PING/PONG

Description

PING and PONG implement a simple keep-alive mechanism between client and server. Once a client establishes a connection to the NATS server, the server will continuously send PING messages to the client at a configurable interval. If the client fails to respond with a PONG message within the configured response interval, the server will terminate its connection. If your connection stays idle for too long, it is cut off.

If the server sends a ping request, you can reply with a pong message to notify the server that you are still interested. You can also ping the server and will receive a pong reply. The ping/pong interval is configurable.

The server uses normal traffic as a ping/pong proxy, so a client that has messages flowing may not receive a ping from the server.

Syntax

PING␍␊

PONG␍␊

Example

The following example shows the demo server pinging the client and finally shutting it down.

telnet demo.nats.io 4222

Trying 107.170.221.32...
Connected to demo.nats.io.
Escape character is '^]'.
INFO {"server_id":"Zk0GQ3JBSrg3oyxCRRlE09","version":"1.2.0","proto":1,"go":"go1.10.3","host":"0.0.0.0","port":4222,"max_payload":1048576,"client_id":2392}
PING
PING
-ERR 'Stale Connection'
Connection closed by foreign host.

+OK/ERR

Description

The -ERR message is used by the server indicate a protocol, authorization, or other runtime connection error to the client. Most of these errors result in the server closing the connection.

Handling of these errors usually has to be done asynchronously.

Syntax

+OK␍␊

-ERR <error message>␍␊

Some protocol errors result in the server closing the connection. Upon receiving these errors, the connection is no longer valid and the client should clean up relevant resources. These errors include:

  • -ERR 'Unknown Protocol Operation': Unknown protocol error

  • -ERR 'Attempted To Connect To Route Port': Client attempted to connect to a route port instead of the client port

  • -ERR 'Authorization Timeout': Client took too long to authenticate to the server after establishing a connection (default 1 second)

  • -ERR 'Maximum Control Line Exceeded': Message destination subject and reply subject length exceeded the maximum control line value specified by the max_control_line server option. The default is 1024 bytes.

  • -ERR 'Parser Error': Cannot parse the protocol message sent by the client

  • -ERR 'Secure Connection - TLS Required': The server requires TLS and the client does not have TLS enabled.

  • -ERR 'Stale Connection': The server hasn't received a message from the client, including a PONG in too long.

  • -ERR 'Maximum Connections Exceeded': This error is sent by the server when creating a new connection and the server has exceeded the maximum number of connections specified by the max_connections server option. The default is 64k.

  • -ERR 'Slow Consumer': The server pending data size for the connection has reached the maximum size (default 10MB).

Protocol error messages where the connection remains open are listed below. The client should not close the connection in these cases.

  • -ERR 'Invalid Subject': Client sent a malformed subject (e.g. sub foo. 90)

When using the updated client protocol (see below), INFO messages can be sent anytime by the server. This means clients with that protocol level need to be able to asynchronously handle INFO messages.

The CONNECT message is the client version of the message. Once the client has established a TCP/IP socket connection with the NATS server, and an message has been received from the server, the client may send a CONNECT message to the NATS server to provide more information about the current connection as well as security information.

verbose: Turns on protocol acknowledgements.

protocol: optional int. Sending 0 (or absent) indicates client supports original protocol. Sending 1 indicates that the client supports dynamic reconfiguration of cluster topology changes by asynchronously receiving messages with known servers it can reconnect to.

no_responders: optional bool. Enable .

Most clients set verbose to false by default. This means that the server should not confirm each message it receives on this connection with a back to the client.

NATS headers are similar, in structure and semantics, to HTTP headers as name: value pairs including supporting multi-value headers. Headers can be mixed case and NATS will preserve case between message publisher and message receiver(s). See also .

The HMSG message is the same as MSG, but extends the message payload with headers. See also .

When the verbose connection option is set to true (the default value), the server acknowledges each well-formed protocol message from the client with a +OK message. Most NATS clients set the verbose option to false using the message

-ERR 'Authorization Violation': Client failed to authenticate to the server with credentials specified in the message

-ERR 'Invalid Client Protocol': Client specified an invalid protocol version in the message

-ERR 'Maximum Payload Violation': Client attempted to publish a message with a payload size that exceeds the max_payload size configured on the server. This value is supplied to the client upon connection in the initial message. The client is expected to do proper accounting of byte size to be sent to the server in order to handle this error synchronously.

-ERR 'Permissions Violation for Subscription to <subject>': The user specified in the message does not have permission to subscribe to the subject.

-ERR 'Permissions Violation for Publish to <subject>': The user specified in the message does not have permissions to publish to the subject.

NATS Protocol Demo
zero allocation byte parser
quick replies for cases where a request is sent to a topic with no responders
ADR-4 NATS Message Headers
ADR-4 NATS Message Headers
CONNECT
INFO
INFO
+OK
INFO
+OK
CONNECT
CONNECT
CONNECT
INFO
CONNECT
CONNECT
INFO
CONNECT
PUB
HPUB
SUB
UNSUB
MSG
HMSG
PING
PONG
+OK
-ERR