@nitrogenbuilder/client-core
Version:
Nitrogen Builder Core Client
39 lines (38 loc) • 1.63 kB
JavaScript
import { io } from 'socket.io-client';
const SOCKET_SERVER_URL = process.env.NODE_ENV === 'nitrogen'
? 'http://localhost:42069?client=true'
: 'https://app.nitrogenbuilder.com?client=true';
export default function createSocket(onConnect, onDisconnect) {
const socket = io(SOCKET_SERVER_URL, {
transports: ['websocket'],
autoConnect: true, // Enable auto connection
reconnection: true, // Enable automatic reconnection
reconnectionAttempts: Infinity, // Unlimited reconnection attempts
reconnectionDelay: 1000, // Initial delay of reconnection (in milliseconds)
reconnectionDelayMax: 5000, // Maximum delay between reconnections (in milliseconds)
randomizationFactor: 0.5, // Randomization factor for the delay between reconnections
});
// Handle connection event
socket.on('connect', () => {
console.log('Connected to the websocket server');
onConnect(socket);
});
// Handle disconnection event
socket.on('disconnect', (reason) => {
console.log('Disconnected from the server:', reason);
onDisconnect(socket);
});
// Handle reconnection event
socket.on('reconnect', (attemptNumber) => {
console.log('Reconnected to the server after', attemptNumber, 'attempts');
});
// Handle reconnection failed event
socket.on('reconnect_failed', () => {
console.error('Reconnection failed after reaching max number of attempts');
});
// Handle error event
socket.on('error', (error) => {
console.error('Connection error:', error);
});
return socket;
}