Websockets
Our Platform offers a socket.io server to be able to develop realtime Apps. This means that you have to use a socket.io library to develop your client.
Socket.IO primarily uses the WebSocket protocol with polling as a fallback option, while providing the same interface. Although it can be used as simply a wrapper for WebSocket, it provides many more features, including broadcasting to multiple sockets, storing data associated with each client, and asynchronous I/O.
socket.io is a JavaScript library for realtime web applications, but you can find native implementations for Android and iOS too.
Getting started with Socket.io
Our socket.io server only subscribes. To authenticate, send values, etc. you have to use the REST API as explained at our App Development Documentation.
To be able to follow this example you will need a session token. You can get the session token via register or login with the respective REST API endpoints, as commented before.
The url to connect to our socket.io server: ws.thethings.io/v2
Topics
You have to subscribe to a topic. Where a topic can be:
- An user’s resource, eg. /me/resources/{{resource}}
- A thing eg. /things/{{thingToken}} . But be careful here, you don't want to make public your thingToken. This option is only recommended for intranets or other private pages under authentication.
Example
At this example, we show how to subscribe to the topic '/me/resources/temperature' , to get the values published in real-time.
In the examples, the {{SOMETHING}} (braces included) indicate variables that you have to replace for a valid value.
// First, you have to connect to thethings.iO’s socket.io server ws.thethings.io , and v2 namespace
var socket = io.connect('https://ws.thethings.io/v2')
// The next step is authenticate with the session token:
socket.on('connect', function () {
socket.emit('authenticate', {sessionToken:"your session token"})
})
// Once we are authenticated we can start subscribing to the things and user’s topics:
socket.on('authenticate',function(data){
if(data.status === 'success'){
socket.emit('subscribe', {
resource : { {topic} } // topic example: '/me/resources/temperature'
})
}
})
// The server will emit on the topic you subscribed. So to get the values use:
socket.on({ {topic} }, function(data){
console.log(data)
})
// Finally we can unsubscribe:
socket.emit('unsubscribe', {
resource : { {topic} }
})
Updated over 1 year ago