itmp.js is a client and server library for the ITMP protocol, written in JavaScript for node.js and the browser.
itmp.js is an OPEN Open Source Project, see the Contributing section to find out what this means.
npm install itmp --save
For the sake of simplicity, let's put the subscriber and the publisher in the same file:
var itmp = require('itmp')
var client = itmp.connect('ws://test.itmp.org')
client.on('connect', function () {
client.subscribe('presence').then(function (err) {
client.publish('presence', 'Hello itmp')
})
})
client.on(client.$message, function (topic, message) {
// message is object
console.log(message)
})
output:
Hello itmp
If you want to run your own itmp server, you can use Itmp.online, and launch it. You can also use a test instance: test.itmp.online is both public.
If you do not want to install a separate server, you can try using the itmp-connection.
to use itmp.js in the browser see the browserify section
If you want to use the new async-await functionality in JavaScript just use itmp.js which uses promises instead of callbacks when possible.
itmp.js bundles a command to interact with a server. In order to have it available on your path, you should install itmp.js globally:
npm install itmp -g
Then, on one terminal
itmp sub -t 'hello' -h 'test.mosquitto.org' -v
On another
itmp pub -t 'hello' -h 'test.mosquitto.org' -m 'from itmp.js'
See itmp help <command>
for the command help.
itmp.connect()
itmp.Client()
itmp.Client#publish()
itmp.Client#subscribe()
itmp.Client#unsubscribe()
itmp.Client#end()
itmp.Client#removeOutgoingMessage()
itmp.Client#reconnect()
itmp.Client#handleMessage()
itmp.Client#connected
itmp.Client#reconnecting
itmp.Client#getLastMessageId()
itmp.Store()
itmp.Store#put()
itmp.Store#del()
itmp.Store#createStream()
itmp.Store#close()
Connects to the server specified by the given url and options and returns a Client.
The URL can be on the following protocols: 'udp', 'serial', 'ws', 'wss'. The URL can also be an object as returned by
URL.parse()
,
in that case the two objects are merged, i.e. you can pass a single
object with both the URL and the connect options.
You can also specify a servers
options with content: [{ host: 'localhost', port: 1883 }, ... ]
, in that case that array is iterated
at every connect.
For all itmp-related options, see the Client constructor.
The Client
class wraps a client connection to an
itmp server over an arbitrary transport method (TCP, TLS,
WebSocket, ecc).
Client
automatically handles the following:
- Regular server pings
- QoS flow
- Automatic reconnections
- Start publishing before being connected
The arguments are:
streamBuilder
is a function that returns a subclass of theStream
class that supports theconnect
event. Typically anet.Socket
.options
is the client connection options (see: the connect packet). Defaults:keepalive
:60
seconds, set to0
to disablereschedulePings
: reschedule ping messages after sending packets (defaulttrue
)clientId
:'itmpjs_' + Math.random().toString(16).substr(2, 8)
clean
:true
, set to false to receive QoS 1 and 2 messages while offlinereconnectPeriod
:1000
milliseconds, interval between two reconnectionsconnectTimeout
:30 * 1000
milliseconds, time to wait before a CONNACK is receivedusername
: the username required by your server, if anypassword
: the password required by your server, if anyincomingStore
: a Store for the incoming packetsoutgoingStore
: a Store for the outgoing packetsqueueEvents
: if connection is broken, queue outgoing QoS zero messages (defaulttrue
)will
: a message that will sent by the server automatically when the client disconnect badly. The format is:topic
: the topic to publishpayload
: the message to publishproperties
: properties of will
resubscribe
: if connection is broken and reconnects, subscribed topics are automatically subscribed again (defaulttrue
)
In case itmps (itmp over tls) is required, the options
object is
passed through to
tls.connect()
.
If you are using a self-signed certificate, pass the rejectUnauthorized: false
option.
Beware that you are exposing yourself to man in the middle attacks, so it is a configuration
that is not recommended for production environments.
function (linkname) {}
Emitted on successful (re)connection.
function () {}
Emitted after a disconnection.
function (link, address, topic, message, options) {}
Emitted when the client receives a publish packet
link
link object of the received packetaddress
address of the sender of the received packettopic
topic of the received packetmessage
payload of the received packetoptions
options of the received packet
Publish a message to a topic
topic
is the topic to publish to,String
message
is the message to publish, any js type except array and object will be surrounded by arrayoptions
is the options to publish with, including:
Subscribe to a topic or topics
topic
is aString
topic to subscribe to or anArray
of topics to subscribe to. itmptopic
wildcard characters are supported (+
- for single level and#
- for multi level)options
is the options to subscribe with, including:callback
-function (topic)
, fired on get message.
Unsubscribe from a topic or topics
topic
is aString
topic or an array of topics to unsubscribe fromcallback
-function
, unsubscribe this handler.
Close the client, accepts the following options:
force
: passing it to true will close the client right away, without waiting for the in-flight messages to be acked. This parameter is optional.options
: options of disconnect.reasonCode
: Disconnect Reason Codenumber
Connect again using the same options as connect()
Boolean : set to true
if the client is connected. false
otherwise.
Boolean : set to true
if the client is trying to reconnect to the server. false
otherwise.
In-memory implementation of the message store.
options
is the store options:clean
:true
, clean inflight messages when close is called (defaulttrue
)
Other implementations of itmp.Store
:
- itmp-level-store which uses Level-browserify to store the inflight data, making it usable both in Node and the Browser.
Adds a packet to the store, a packet is
anything that has a messageId
property.
The callback is called when the packet has been stored.
Removes a packet from the store, a packet is
anything that has a messageId
property.
The callback is called when the packet has been removed.
Closes the Store.
The itmp.js bundle is available through http://unpkg.com, specifically at https://unpkg.com/itmp/dist/itmp.min.js. See http://unpkg.com for the full documentation on version ranges.
var itmp = require('itmp')
var client = itmp.connect('wxs://test.itmp.online')
import { connect } from 'itmp';
const client = connect('wxs://test.itmp.online');
In order to use itmp.js as a browserify module you can either require it in your browserify bundles or build it as a stand alone module. The exported module is AMD/CommonJs compatible and it will add an object in the global space.
npm install -g browserify // install browserify
cd node_modules/itmp
npm install . // install dev dependencies
browserify itmp.js -s itmp > browseritmp.js // require itmp in your client-side app
Just like browserify, export itmp.js as library. The exported module would be var itmp = xxx
and it will add an object in the global space. You could also export module in other formats (AMD/CommonJS/others) by setting output.libraryTarget in webpack configuration.
npm install -g webpack // install webpack
cd node_modules/itmp
npm install . // install dev dependencies
webpack itmp.js ./browseritmp.js --output-library itmp
you can then use itmp.js in the browser with the same api than node's one.
<html>
<head>
<title>test Ws itmp.js</title>
</head>
<body>
<script src="./browseritmp.js"></script>
<script>
var client = itmp.connect() // you add a ws:// url here
client.subscribe("itmp/demo")
client.on(client.$message, function (topic, payload) {
alert([topic, payload].join(": "))
client.end()
})
client.publish("itmp/demo", "hello world!")
</script>
</body>
</html>
Your server should accept websocket connection (see itmp over Websockets to setup).
Here is how QoS works:
- QoS 0 : received at most once : The packet is sent, and that's it. There is no validation about whether it has been received.
- QoS 1 : received at least once : The packet is sent and stored as long as the client has not received a confirmation from the server. itmp ensures that it will be received, but there can be duplicates.
- QoS 2 : received exactly once : Same as QoS 1 but there is no duplicates.
About data consumption, obviously, QoS 2 > QoS 1 > QoS 0, if that's a concern to you.
This repo bundles TypeScript definition files for use in TypeScript projects and to support tools that can read .d.ts
files.
Before you can begin using these TypeScript definitions with your project, you need to make sure your project meets a few of these requirements:
- TypeScript >= 2.1
- Set tsconfig.json:
{"compilerOptions" : {"moduleResolution" : "node"}, ...}
- Includes the TypeScript definitions for node. You can use npm to install this by typing the following into a terminal window:
npm install --save-dev @types/node
itmp.js is an OPEN Open Source Project. This means that:
Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
See the CONTRIBUTING.md file for more details.
MIT