Linux:MQTT通信协议之一 -- apt-get命令搭建mosquitto与简单测试

MQTT

Message Queuing Telemetry Transport是一个基于TCP/IP的轻量级、灵活的即时通讯协议,多用于IOT物联网开发(这里假设你已经了解过MQTT是怎样的一个协议了,所以只是简单说明一下,想了解更多可以去搜索引擎找专业解答,如果还不想搜索,本文末参考文章部分也有提供IBM的官方说明链接)。
Linux:MQTT通信协议之一 -- apt-get命令搭建mosquitto与简单测试_第1张图片
Linux:MQTT通信协议之一 -- apt-get命令搭建mosquitto与简单测试_第2张图片


通信模式

  • 服务器端:MQTT服务器非常多,如apache的ActiveMQ,emtqqd,HiveMQ,Emitter,Mosquitto,Moquette等等;上图中的Broker属于服务器端,处理客户端的网络连接和订阅等请求。
  • 客户端:Publisher和Subscriber都属于客户端,连接服务器端进行发布/订阅消息。

上面图片可以看到MQTT采用的是订阅/发布模式,客户端通过TCP连接到服务器端,与此同时订阅或者发布某个主题的数据,将数据发送到MQTT服务器端后,服务器端再根据订阅者所订阅的主题将这些消息进行转发。


设置发布服务质量:

  • QoS =0:至多一次,可能会出现丢包的情况,使用在对实时性要求不高的情况,如环境传感器数据;
  • QoS =1:至少一次,保证包会到达目的地,有可能出现重包;
  • QoS =2:刚好一次,保证包会到达目的地,不会出现重包的现象。

订阅多个主题

  • 主题层级分隔符/
  • 多层(大于等于0层)通配符#,必须作为最后一个字符而不能处于中间;
  • 单层通配符+,仅支持匹配一层,可以在主题末端,也可以在中间。

比如有以下主题:

world
world/china
world/china/beijing
world/china/beijing/chaoyang
world/usa

那么如果订阅了world/china/#则可以匹配以下主题:

world/china				// 支持0层
world/china/beijing
world/china/beijing/chaoyang

如果订阅了world/+则可以匹配以下主题(注意这里不能匹配到world):

world/china
world/usa

如果订阅了world/+/beijing则可以匹配(注意+不能换成#,因为#只能在末端):

world/china/beijing

Ubuntu安装mosquitto

① 安装服务器端

sudo apt-get install mosquitto

完成后服务器端就已经搭建好了,系统会自动运行mosquitto,默认端口为1883。

② 查看状态命令

sudo systemctl status mosquitto

③ 安装客户端
前面服务器端搭建好了,但是客户端还没有安装。这一步是可选的,如果需要在终端上测试MQTT订阅/发布的通信就需要执行这一步,这里我们也安装上去才有后续的这些测试。

sudo apt install mosquitto-clients

测试(默认配置)

Linux:MQTT通信协议之一 -- apt-get命令搭建mosquitto与简单测试_第3张图片
(需要注意的是,ccc这条消息是没有被订阅端接收到的,原因就在于‘+’只匹配一层。)


服务器设置密码 / 端口

前面服务器没有设置密码和端口,这样谁都可以连接服务器进行订阅消息,那显然不安全,接下来设置密码:

① 生成密码文件,后续需要输入2次密码进行确认

sudo mosquitto_passwd -c /etc/mosquitto/myMQTTpasswd 用户名

② 修改配置文件/etc/mosquitto/conf.d/myMQTT.conf内容如下

password_file /etc/mosquitto/myMQTTpasswd

port 2020

其中,内容为指定密码文件用于加密连接(会默认关闭匿名连接,无需显式关闭)、设置连接端口。

③ 重启生效

重启服务器程序:
可以执行命令查看进程号:ps aux | grep mosquitto | grep -v grep
执行命令杀死进程:kill -9 进程号
指定配置文件启动进程后台运行:mosquitto -c /etc/mosquitto/conf.d/myMQTT.conf -d

重启系统:
重启系统就不需要指定配置文件,在/etc/mosquitto/conf.d/README里面指出会以该目录下.conf结尾的文件作为配置文件。

以上两者方法选择其中一种即可。


测试(指定密码和端口)

此时如果还是使用前面的无密码的运行方式,会发现已经被拒绝连接了(如Error: Connection refused),此时就需要加上-p 端口号-u 用户名-P 密码重新连接。
如果想更深入的测试,可以参考附加内容里面的参数与配置。


参考文章

官方说明 :IBM:初识 MQTT
源码/文档:Eclipse Mosquitto(重点关注)
参考博客 :Linux安装测试MQTT
参考博客 :利用MQTT一次订阅多个主题


附加内容(相关参数说明)

book@Ubuntu:~$ mosquitto --help
mosquitto version 1.4.8 (build date Tue, 18 Jun 2019 11:59:34 -0300)

mosquitto is an MQTT v3.1 broker.

Usage: mosquitto [-c config_file] [-d] [-h] [-p port]

 -c : specify the broker config file.
 -d : put the broker into the background after starting.
 -h : display this help.
 -p : start the broker listening on the specified port.
      Not recommended in conjunction with the -c option.
 -v : verbose mode - enable all logging types. This overrides
      any logging options given in the config file.

See http://mosquitto.org/ for more information.
book@Ubuntu:~$ mosquitto_sub --help
mosquitto_sub is a simple mqtt client that will subscribe to a single topic and print all messages it receives.
mosquitto_sub version 1.4.8 running on libmosquitto 1.4.8.

Usage: mosquitto_sub [-c] [-h host] [-k keepalive] [-p port] [-q qos] [-R] -t topic ...
                     [-C msg_count] [-T filter_out]
                     [-A bind_address] [-S]
                     [-i id] [-I id_prefix]
                     [-d] [-N] [--quiet] [-v]
                     [-u username [-P password]]
                     [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]
                     [{--cafile file | --capath dir} [--cert file] [--key file]
                      [--ciphers ciphers] [--insecure]]
                     [--psk hex-key --psk-identity identity [--ciphers ciphers]]
                     [--proxy socks-url]
       mosquitto_sub --help

 -A : bind the outgoing socket to this host/ip address. Use to control which interface
      the client communicates over.
 -c : disable 'clean session' (store subscription and pending messages when client disconnects).
 -C : disconnect and exit after receiving the 'msg_count' messages.
 -d : enable debug messages.
 -h : mqtt host to connect to. Defaults to localhost.
 -i : id to use for this client. Defaults to mosquitto_sub_ appended with the process id.
 -I : define the client id as id_prefix appended with the process id. Useful for when the
      broker is using the clientid_prefixes option.
 -k : keep alive in seconds for this client. Defaults to 60.
 -N : do not add an end of line character when printing the payload.
 -p : network port to connect to. Defaults to 1883.
 -P : provide a password (requires MQTT 3.1 broker)
 -q : quality of service level to use for the subscription. Defaults to 0.
 -R : do not print stale messages (those with retain set).
 -S : use SRV lookups to determine which host to connect to.
 -t : mqtt topic to subscribe to. May be repeated multiple times.
 -T : topic string to filter out of results. May be repeated.
 -u : provide a username (requires MQTT 3.1 broker)
 -v : print published messages verbosely.
 -V : specify the version of the MQTT protocol to use when connecting.
      Can be mqttv31 or mqttv311. Defaults to mqttv31.
 --help : display this message.
 --quiet : don't print error messages.
 --will-payload : payload for the client Will, which is sent by the broker in case of
                  unexpected disconnection. If not given and will-topic is set, a zero
                  length message will be sent.
 --will-qos : QoS level for the client Will.
 --will-retain : if given, make the client Will retained.
 --will-topic : the topic on which to publish the client Will.
 --cafile : path to a file containing trusted CA certificates to enable encrypted
            certificate based communication.
 --capath : path to a directory containing trusted CA certificates to enable encrypted
            communication.
 --cert : client certificate for authentication, if required by server.
 --key : client private key for authentication, if required by server.
 --ciphers : openssl compatible list of TLS ciphers to support.
 --tls-version : TLS protocol version, can be one of tlsv1.2 tlsv1.1 or tlsv1.
                 Defaults to tlsv1.2 if available.
 --insecure : do not check that the server certificate hostname matches the remote
              hostname. Using this option means that you cannot be sure that the
              remote host is the server you wish to connect to and so is insecure.
              Do not use this option in a production environment.
 --psk : pre-shared-key in hexadecimal (no leading 0x) to enable TLS-PSK mode.
 --psk-identity : client identity string for TLS-PSK mode.
 --proxy : SOCKS5 proxy URL of the form:
           socks5h://[username[:password]@]hostname[:port]
           Only "none" and "username" authentication is supported.

See http://mosquitto.org/ for more information.
book@Ubuntu:~$ mosquitto_pub --help
mosquitto_pub is a simple mqtt client that will publish a message on a single topic and exit.
mosquitto_pub version 1.4.8 running on libmosquitto 1.4.8.

Usage: mosquitto_pub [-h host] [-k keepalive] [-p port] [-q qos] [-r] {-f file | -l | -n | -m message} -t topic
                     [-A bind_address] [-S]
                     [-i id] [-I id_prefix]
                     [-d] [--quiet]
                     [-M max_inflight]
                     [-u username [-P password]]
                     [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]
                     [{--cafile file | --capath dir} [--cert file] [--key file]
                      [--ciphers ciphers] [--insecure]]
                     [--psk hex-key --psk-identity identity [--ciphers ciphers]]
                     [--proxy socks-url]
       mosquitto_pub --help

 -A : bind the outgoing socket to this host/ip address. Use to control which interface
      the client communicates over.
 -d : enable debug messages.
 -f : send the contents of a file as the message.
 -h : mqtt host to connect to. Defaults to localhost.
 -i : id to use for this client. Defaults to mosquitto_pub_ appended with the process id.
 -I : define the client id as id_prefix appended with the process id. Useful for when the
      broker is using the clientid_prefixes option.
 -k : keep alive in seconds for this client. Defaults to 60.
 -l : read messages from stdin, sending a separate message for each line.
 -m : message payload to send.
 -M : the maximum inflight messages for QoS 1/2..
 -n : send a null (zero length) message.
 -p : network port to connect to. Defaults to 1883.
 -P : provide a password (requires MQTT 3.1 broker)
 -q : quality of service level to use for all messages. Defaults to 0.
 -r : message should be retained.
 -s : read message from stdin, sending the entire input as a message.
 -S : use SRV lookups to determine which host to connect to.
 -t : mqtt topic to publish to.
 -u : provide a username (requires MQTT 3.1 broker)
 -V : specify the version of the MQTT protocol to use when connecting.
      Can be mqttv31 or mqttv311. Defaults to mqttv31.
 --help : display this message.
 --quiet : don't print error messages.
 --will-payload : payload for the client Will, which is sent by the broker in case of
                  unexpected disconnection. If not given and will-topic is set, a zero
                  length message will be sent.
 --will-qos : QoS level for the client Will.
 --will-retain : if given, make the client Will retained.
 --will-topic : the topic on which to publish the client Will.
 --cafile : path to a file containing trusted CA certificates to enable encrypted
            communication.
 --capath : path to a directory containing trusted CA certificates to enable encrypted
            communication.
 --cert : client certificate for authentication, if required by server.
 --key : client private key for authentication, if required by server.
 --ciphers : openssl compatible list of TLS ciphers to support.
 --tls-version : TLS protocol version, can be one of tlsv1.2 tlsv1.1 or tlsv1.
                 Defaults to tlsv1.2 if available.
 --insecure : do not check that the server certificate hostname matches the remote
              hostname. Using this option means that you cannot be sure that the
              remote host is the server you wish to connect to and so is insecure.
              Do not use this option in a production environment.
 --psk : pre-shared-key in hexadecimal (no leading 0x) to enable TLS-PSK mode.
 --psk-identity : client identity string for TLS-PSK mode.
 --proxy : SOCKS5 proxy URL of the form:
           socks5h://[username[:password]@]hostname[:port]
           Only "none" and "username" authentication is supported.

See http://mosquitto.org/ for more information.
book@Ubuntu:~$ mosquitto_passwd --help
mosquitto_passwd is a tool for managing password files for mosquitto.

Usage: mosquitto_passwd [-c | -D] passwordfile username
       mosquitto_passwd -b passwordfile username password
       mosquitto_passwd -U passwordfile
 -b : run in batch mode to allow passing passwords on the command line.
 -c : create a new password file. This will overwrite existing files.
 -D : delete the username rather than adding/updating its password.
 -U : update a plain text password file to use hashed passwords.

See http://mosquitto.org/ for more information.

你可能感兴趣的:(Linux)