NodeJs WebSocket
Publish with NodeJS
How to subscribe? see here
You can use following two ways to publish messages/events on the WebSocket Channel Rooms using NodeJS from server-side.
1. Publish with PieSocket NodeJS SDK
Install PieSocket NodeJS SDK using NPM
npm i piesocket-nodejs
Initialize PieSocket class
const PieSocket = require("piesocket-nodejs");
var piesocket = new PieSocket({
clusterId: 'YOUR_CLUSTER_ID',
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_API_SECRET'
});
You are ready to publish messages as many times as you wish:
piesocket.publish(roomId, data);
2. Publish with HTTP Request
Use the following code snippet to publish a message on a WebSocket Room with NodeJS.
var unirest = require('unirest');
var payload = {
"key": "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm", //Demo key, get yours at https://piesocket.com
"secret": "d8129f82f8dd71910aa4a7efa30a7297", //Demo secret, get yours at https://piesocket.com
"roomId": 1,
"message": {"event":"new-message","data":"Hello"}
}
var req = unirest('POST', 'https://CLUSTER_ID.piesocket.com/api/publish')
.headers({
'Content-Type': 'application/json'
})
.send(JSON.stringify(payload))
.end(function(res) {
if (res.error) throw new Error(res.error);
console.log(res.raw_body);
});
This sends a JSON message to WebSocket room 1, to send a string, replace "message": { "text": "Hello world!" } with "message": “Hello world!”
