Develop a publishing client
Use the Diffusion™ JavaScript® API to develop a Node.js client that creates a JSON topic and publishes updates to it.
- Install Node.js on your development system.
For more information, see https://nodejs.org/en/
- Install the Diffusion
JavaScript library on your development system.
npm install diffusion
- Create a JavaScript file, publisher.js, to contain your client.
- Include the Diffusion
JavaScript library at the top of your
publisher.js file.
var diffusion = require('diffusion');
- Create a connection from the page to the Diffusion server.
diffusion.connect({ host : 'localhost', port : '8080', principal : 'client', credentials : 'password' }).then(function(session) { console.log('Connected!'); } );
- Create a JSON topic called topic/json:
.then(function(session) { console.log('Connected!'); session.topics.add('topic/json', diffusion.topics.TopicType.JSON); }
The add() method takes the name of the topic and the topic type.
- Update the topic with a timestamp:
var d = new Date(); session.topics.update('topic/json', { "timestamp" : d.getTime() });
The update() method takes the name of the topic and a JSON object.
- Wrap the update in a loop function that causes an update to occur every second:
setInterval(function() { var d = new Date(); session.topics.update('topic/json', { "timestamp" : d.getTime() }); }, 1000);
- Run the Node.js client:
node publisher.js
Full example
The following example code shows a Node.js JavaScript client that connects to the Diffusion server, creates a JSON topic, and publishes an update to it.
var diffusion = require('diffusion'); diffusion.connect({ host : 'localhost', port : '8080', principal : 'control', credentials : 'password' }).then(function(session) { console.log('Connected!'); // Create a JSON topic session.topics.add('topic/json', diffusion.topics.TopicType.JSON); // Start updating the topic every second setInterval(function() { var d = new Date(); session.topics.update('topic/json', { "timestamp" : d.getTime() }); }, 1000); });
To run the example:
- Install Node.js.
For more information, see https://nodejs.org/en/
- Install the Diffusion
JavaScript library on your development system.
npm install diffusion
- Copy the provided code into a file called publisher.js
- Update the connect method to include the URL of your Diffusion server.
- If you have changed the default security configuration, change the principal and credentials to those of a user that has the and permissions.
- Use Node.js to run your publishing client from the command line.
node publisher.js
Publish using other Diffusion APIs:
- Java
- .NET
- JavaScript
- Apple
- Android
- C