feat: add websocket store
This commit is contained in:
@@ -0,0 +1,56 @@
|
|||||||
|
import { create } from 'zustand';
|
||||||
|
import { useInventoryStore } from './useInventoryStore';
|
||||||
|
|
||||||
|
interface WebsocketState {
|
||||||
|
socket: WebSocket | null;
|
||||||
|
isConnected: boolean;
|
||||||
|
connect: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useWebsocketStore = create<WebsocketState>((set, get) => ({
|
||||||
|
socket: null,
|
||||||
|
isConnected: false,
|
||||||
|
|
||||||
|
connect: () => {
|
||||||
|
if (get().socket) return;
|
||||||
|
|
||||||
|
const ws = new WebSocket('ws://localhost:4444');
|
||||||
|
|
||||||
|
ws.onopen = () => {
|
||||||
|
console.log('Connected to Spoofer Engine');
|
||||||
|
set({ socket: ws, isConnected: true });
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onclose = () => {
|
||||||
|
console.log('Disconnected. Retrying in 2s...');
|
||||||
|
set({ socket: null, isConnected: false });
|
||||||
|
setTimeout(() => get().connect(), 2000);
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onerror = (err) => {
|
||||||
|
console.error('WS Error:', err);
|
||||||
|
ws.close();
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onmessage = (msg) => {
|
||||||
|
try {
|
||||||
|
const payload = JSON.parse(msg.data);
|
||||||
|
if (payload.action === 'init_config')
|
||||||
|
useInventoryStore.getState().importProfile(payload.data);
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to parse WS message", e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
useInventoryStore.subscribe((newState) => {
|
||||||
|
const { socket, isConnected } = useWebsocketStore.getState();
|
||||||
|
|
||||||
|
if (isConnected && socket) {
|
||||||
|
socket.send(JSON.stringify({
|
||||||
|
action: "sync_inventory",
|
||||||
|
data: newState
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user