Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MQTT 学习 #23

Open
nonocast opened this issue Mar 13, 2020 · 0 comments
Open

MQTT 学习 #23

nonocast opened this issue Mar 13, 2020 · 0 comments

Comments

@nonocast
Copy link
Owner

nonocast commented Mar 13, 2020

MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议),是一种基于发布/订阅(publish/subscribe)模式的“轻量级”通讯协议,该协议构建于TCP/IP协议上,由IBM在1999年发布。MQTT最大优点在于,可以以极少的代码和有限的带宽,为连接远程设备提供实时可靠的消息服务。作为一种低开销、低带宽占用的即时通讯协议,使其在物联网、小型设备、移动应用等方面有较广泛的应用。

MQTT官网是mqtt.org, 目前主流版本是3.1.1 (2014年), 最新版本是5.0 (2019年), 协议文档可以看mcxiaoke/mqtt,翻译的非常好。

Broker

我们称mqtt server为broker,在此之前先搞清楚broker, agent, proxy 3个概念:

  • Broker (经纪人): 是为促成他人交易,充当订约居间人,为委托方提供订约的信息、机会和条件的主体。Broker是一个独立主体,但没有自主决策能力,只负责订约过程。
  • Agent (代理人): 是行使被代理者的权力,完成相关的使命或者任务主体。Agent是一个独立主体,负责完成任务但不负责执行任务,Agent具有一定的自主决策能力,如对服务请求的选择。
  • Proxy (代理): 是指行为代理,不是一个主体。Proxy是完全的传递者,如请求和响应的转发,操作控制的传递。

以买卖房子为例, proxy只是个简单的传话筒, broker就是房产中介撮合买卖双方, agent是卖方或者买方全权委托的代理人, 有权决定卖不卖或者买不买。

MQTT首先是消息队列 (message queue), 消息队列就一定有消费者和生产者两个角色, 消息队列在这两个角色之间扮演了拉皮条的角色,所以用borker。什么是server? 一个web server更多的是单边操作,只需要处理browser发过来的请求,这就是server和broker的区别。

在系统设计时,可以将mqtt broker看作和rabbitmq, zeromq等方式处理,目前比较流行的是:

前者是C++, 后者是Erlang。

如果你需要将broker整合进node service,之前社区用的多的是mosca, 后来作者更新为aedes, 改进了性能和插件体系。

const debug = require('debug')('app');
const aedes = require('aedes')();
const logging = require('aedes-logging');
const server = require('net').createServer(aedes.handle);
const port = 1883;

// logging({
//   instance: aedes,
//   server: server
// });

aedes.on('clientReady', client => {
  debug('client connected', client.id);
});

aedes.on('clientDisconnect', client => {
  debug('client disconnected', client.id);
});

aedes.on('publish', (packet, client) => {
  debug('publish', new String(packet.payload));
});

server.listen(port, function () {
  debug('server started and listening on port', port);
})

直接开个MQTTX模拟一下客户端就能测试了,非常方便。

参考:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant