Linux:MQTT通信协议之一 -- mqtt基本概念、apt-get命令搭建mosquitto服务器及简单测试

1、MQTT是什么

Message Queuing Telemetry Transport是一个基于TCP/IP的轻量级、灵活的即时通讯协议,多用于IOT物联网开发(这里假设你已经了解过MQTT是怎样的一个协议了,所以只是简单说明一下,想了解更多可以去搜索引擎找专业解答,如果还不想搜索,本文末参考文章部分也有提供IBM的官方说明链接)。
在这里插入图片描述
在这里插入图片描述


2、MQTT通信模式

  • 服务器端:MQTT服务器非常多,如apache的ActiveMQ,emtqqd,HiveMQ,Emitter,Mosquitto,Moquette等等,我们主要研究Mosquitto。图一的Broker和图二的“代理”都属于服务器端,负责处理客户端的网络连接和订阅等请求。
  • 客户端:Publisher和Subscriber都属于客户端,连接服务器端进行发布/订阅消息。

从上面图片可以看到,topic可以理解成主题/消息类型,payload可以理解为消息内容。那么从图二就可以很容易理解它的通信模式。订阅者先是订阅了topic主题的消息,而当发布端发布了topic主题的消息payload就会经过代理(服务器端)的“筛选”转发给匹配的topic的订阅者。


3、MQTT发布服务质量

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

4、MQTT遗嘱消息

Last Will & Testament,连接服务器端时,订阅端和发布端都可以选择性的设置遗嘱信息。一般来说,客户端主动调用disconnect退出时是不会发布遗嘱信息的,只有当非正常退出时(如网络异常、客户端闪退等情况)才会发布遗嘱消息。另外,遗嘱信息可以设置是否保留,如果设置了保留,当该客户端异常断开之后,不仅是当前订阅了该主题的订阅端收到遗嘱消息,后续有客户端连接服务器时,也会收到服务器所保留的遗嘱等消息。


5、MQTT主题筛选

  • 主题层级分隔符“/
  • 多层(大于等于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

6、Ubuntu安装mosquitto

① 安装服务器端

sudo apt-get install mosquitto

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

② 查看状态命令

sudo systemctl status mosquitto

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

sudo apt install mosquitto-clients

7、测试(默认配置)

在这里插入图片描述
(需要注意的是,ccc这条消息是没有被订阅端接收到的,原因就在于‘+’只匹配一层。)


8、设置服务器端密码 / 端口

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

① 生成密码文件

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

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

password_file /etc/mosquitto/myMQTTpasswd

port 2020

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

③ 重启生效

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

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

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


9、测试(密码连接)

此时如果还是使用前面的无密码的运行方式,会发现已经被拒绝连接了(如Error: Connection refused),此时就需要加上-p 端口号-u 用户名-P 密码重新连接。

如果想更深入的测试,可以参考附加内容里面的参数与配置。

本篇文章是通过apt-get命令来搭建mosquitto服务器,下一篇文章我们尝试一下编译源码来搭建。编译源码的好处就是我们可以查看源码,使用源码提供给我们的一些接口,实现自定义的MQTT通讯程序。


10、参考文章

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


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

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.

猜你喜欢

转载自blog.csdn.net/weixin_44498318/article/details/106551797