itmp v2.0.13
ITMP
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.
Installation
npm install itmp --saveExample
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 itmpIf 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
Promise support
If you want to use the new async-await functionality in JavaScript just use itmp.js which uses promises instead of callbacks when possible.
Command Line Tools
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 -gThen, on one terminal
itmp sub -t 'hello' -h 'test.mosquitto.org' -vOn another
itmp pub -t 'hello' -h 'test.mosquitto.org' -m 'from itmp.js'See itmp help <command> for the command help.
API
- 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()
itmp.connect(url, options)
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.
itmp.Client(streamBuilder, options)
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:
streamBuilderis a function that returns a subclass of theStreamclass that supports theconnectevent. Typically anet.Socket.optionsis the client connection options (see: the connect packet). Defaults:keepalive:60seconds, set to0to 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:1000milliseconds, interval between two reconnectionsconnectTimeout:30 * 1000milliseconds, 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.
Event Client.$connect
function (linkname) {}
Emitted on successful (re)connection.
Event Client.$disconnect
function () {}
Emitted after a disconnection.
Event Client.$message
function (link, address, topic, message, options) {}
Emitted when the client receives a publish packet
linklink object of the received packetaddressaddress of the sender of the received packettopictopic of the received packetmessagepayload of the received packetoptionsoptions of the received packet
itmp.Client#publish(topic, message, options)
Publish a message to a topic
topicis the topic to publish to,Stringmessageis the message to publish, any js type except array and object will be surrounded by arrayoptionsis the options to publish with, including:
itmp.Client#subscribe(topic/topic array, options, callback)
Subscribe to a topic or topics
topicis aStringtopic to subscribe to or anArrayof topics to subscribe to. itmptopicwildcard characters are supported (+- for single level and#- for multi level)optionsis the options to subscribe with, including:callback-function (topic), fired on get message.
itmp.Client#unsubscribe(topic/topic array, callback)
Unsubscribe from a topic or topics
topicis aStringtopic or an array of topics to unsubscribe fromcallback-function, unsubscribe this handler.
itmp.Client#end(force, options)
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
itmp.Client#reconnect()
Connect again using the same options as connect()
itmp.Client#connected
Boolean : set to true if the client is connected. false otherwise.
itmp.Client#reconnecting
Boolean : set to true if the client is trying to reconnect to the server. false otherwise.
itmp.Store(options)
In-memory implementation of the message store.
optionsis 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.
itmp.Store#put(packet)
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.
itmp.Store#del(packet, cb)
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.
itmp.Store#close(cb)
Closes the Store.
Browser
Via CDN
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.
Example(js)
var itmp = require('itmp')
var client = itmp.connect('wxs://test.itmp.online')Example(ts)
import { connect } from 'itmp';
const client = connect('wxs://test.itmp.online');Browserify
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 appWebpack
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 itmpyou 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).
About QoS
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.
Usage with TypeScript
This repo bundles TypeScript definition files for use in TypeScript projects and to support tools that can read .d.ts files.
Pre-requisites
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
Contributing
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.
License
MIT
2 years ago
3 years ago
3 years ago
4 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago

