Establishing a Websocket Connection
To begin receiving messages in real-time, you'll need to establish a websocket connection from your client-side application. This process involves authenticating your client with the Ripplefy websocket using the authentication token generated in the "Registering a New User" section.
Here's a JavaScript example demonstrating how to open a websocket connection:
async function openWS(user, token) {
// If your WebSocket server requires an 'Origin' header, the browser will automatically set this header based on the location of your page.
// If your server is running on a different domain, you may need to handle 'Origin' checking on your server-side code to allow the correct origins.
// const options = { headers: { Origin: 'http://localhost' } };
// const ws = new WebSocket(url, options);
const url = `wss://ws.ripplesignal.co/?token=${token}`;
const ws = new WebSocket(url);
// TODO: add headers
let intervalId = null;
ws.onopen = () => {
console.log('WebSocket connection established.');
// (Optional) Ping the server every 5 seconds to keep the connection open
intervalId = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send('ping');
}
}, 5000);
};
ws.onmessage = (message) => {
console.log('Received message:', message.data);
};
ws.onclose = (event) => {
console.log('WebSocket connection closed.', event.reason);
clearInterval(intervalId);
// Consider regenerating user's authentication token and reopening the websocket connection
// createUserAuthToken(user).then(token => openWS(user, token));
};
ws.onerror = (error) => {
console.log('WebSocket error:', error.message);
clearInterval(intervalId);
// Consider regenerating user's authentication token and reopening the websocket connection
// createUserAuthToken(user).then(token => openWS(user, token));
};
}
async function createUserAuthToken(userID) {
// Implement
return Promise.resolve();
}
// Call this function to initiate the websocket connection
let user = `{userID}::{sessionID}`;
createUserAuthToken(user).then(token => openWS(user, token));