I am attempting to utilize Centrifugo along with SockJS-client to monitor the server connection status. The versions I am currently using for Centrifugo and SockJS-client are 'centrifuge': '^1.5.0' and 'sockjs-client': '^1.6.1' respectively.
My goal is to determine whether the server connection is established or disconnected using Centrifugo and SockJS-client. Below is the code from my centrifugo.service.js file.
import SockJS from "sockjs-client";
import Centrifuge from "centrifuge";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
import { ref, watch } from "vue";
import { useNotification } from "@kyvg/vue3-notification";
import { useHelper } from "@/services/helper.sevice.js";
import { useUtilities } from "@/services/utilities.js";
export const useCentrifuge = () => {
const store = useStore();
const router = useRouter();
const route = useRoute();
const { notify } = useNotification();
const { validateResponse, ping } = useHelper();
const { getPublicPath, getCentrifugePath } = useUtilities();
const url = getCentrifugePath();
let connection = null;
const connectionStatus = ref("disconnected");
const getNotificationMessage = (notice) => {
const array = notice.split("|");
let notificationMessage = array[1];
if (!notificationMessage === undefined) {
notificationMessage = "";
}
return notificationMessage;
};
const callbacks = () => {
return {
message: function (message) {
console.log(message.data.clear, document.hidden);
if (
message.data.clear &&
message.data.clear === "user" &&
document.hidden
) {
store.reset();
store.dispatch("login/updateStopLogin", true);
localStorage.setItem("stopLogin", "true");
window.location.href = window.location.href.split("#")[0];
return;
}
if (
message.data.clear &&
(message.data.clear === "chat" || message.data.clear === "all") &&
message.data.id
) {
(async () => {
await refreshListFromCallback();
})();
const currentContactId = message.data.id;
setTimeout(async () => {
let response = await getChatItems(currentContactId);
if (response.status == 200) {
response = await validateResponse(response);
let temp = [];
temp =
response.data && response.data.items ? response.data.items : [];
if (response.data) {
const selectedCurrentContactId =
store.getters[`${route.name}/getCurrentContactId`]();
if (currentContactId === selectedCurrentContactId) {
store.dispatch(`${route.name}/updateChatItems`, temp);
}
} else {
router.push(response.error.path);
return;
}
}
}, 300);
}
setTimeout(async () => {
const isDesktop =
window.Notification && Notification.permission === "granted";
if (isDesktop && message.data.notice) {
const notification = new Notification("Traktel", {
body: await getNotificationMessage(message.data.notice),
icon: `${getPublicPath()}img/icons/t_logo.png`,
requireInteraction: true,
});
notification.onclick = function () {
window.focus();
};
} else if (message.data.notice) {
if (!isDesktop) {
const showNotifications = store.getters[
"traktel/getCurrentShowNotifications"
]
? store.getters["traktel/getCurrentShowNotifications"]()
: false;
if (showNotifications) {
const text = await getNotificationMessage(message.data.notice);
notify({
title: "Traktel",
text,
});
}
}
}
}, 100);
},
join: function (message) {
console.log("join", message);
},
leave: function (message) {
console.log("leave", message);
},
subscribe: function (context) {
console.log("subscribe", context);
},
error: function (err) {
console.log("error", err);
ping();
},
unsubscribe: function (context) {
console.log("unsubscribe", context);
},
};
};
const connect = async () => {
const channelData = store.getters["login/getChannelData"]();
if (
channelData &&
channelData.mqUser != "" &&
channelData.mqTimestamp != "" &&
channelData.mqToken != ""
) {
console.log("SockJS URL:", url);
const sock = new SockJS(url);
console.log("Centrifuge URL:", url);
const centrifuge = new Centrifuge({
url,
user: channelData.mqUser,
timestamp: channelData.mqTimestamp?.toString(),
token: channelData.mqToken,
debug: true,
});
console.log("connecting to sockJS...");
let subscription = null;
sock.onopen = () => {
console.log("opened");
};
console.log("unsubscribing....");
if (subscription !== null) {
subscription.unsubscribe();
}
console.log("subscribing....");
subscription = centrifuge.subscribe(
channelData.mqUser?.trim(),
callbacks()
);
centrifuge.on("connect", () => {
console.log("connected");
connection = centrifuge;
connectionStatus.value = connection._status;
console.log(" connectionStatus.value,,,,,,,", connectionStatus.value);
store.dispatch(
"traktel/updateCentrifugoConnectionStatus",
connection._status
);
});
centrifuge.on("error", (error) => {
console.log(error);
ping();
});
centrifuge.on("disconnect", () => {
console.log("disconnect");
connection = centrifuge;
connectionStatus.value = connection._status;
console.log(" connectionStatus.value,,,,,,,", connectionStatus.value);
store.dispatch(
"traktel/updateCentrifugoConnectionStatus",
connection._status
);
ping();
});
centrifuge.connect();
await new Promise((resolve) => {
centrifuge.on("connect", resolve);
});
connectionStatus.value = centrifuge.isConnected()
? "connected"
: "disconnected";
console.log("centrifuge.connect()...........", connectionStatus.value);
}
};
const connectToMessageServer = async () => {
await disconnectFromMessageServer();
const status = await connect();
console.log("connectionStatushghghgh", status);
return status;
};
watch(connectionStatus, (newStatus) => {
console.log("connectionStatus changed:", newStatus);
});
const disconnectFromMessageServer = async () => {
console.log("disconnecting centrifugo...");
if (connection !== null) {
connection.disconnect();
store.dispatch("traktel/updateCentrifugoConnectionStatus", undefined);
}
};
return {
connection,
connect,
connectToMessageServer,
connectionStatus,
disconnectFromMessageServer,
};
};```
can any one help me identifying my problem?
I was expecting to know the states of the server whether it is connected or disconnected. but currently the error is displaying when the connect function is excuted