Show authenticated unique online player count on home screen
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
import type { GameSessionAuth } from '../shared/p2p-types.js';
|
||||
|
||||
export function createPresence(counter: HTMLElement) {
|
||||
let socket: Socket | undefined, sessionId = '';
|
||||
const unknown = () => { counter.textContent = '접속 확인 중'; };
|
||||
window.addEventListener('pagehide', () => { socket?.disconnect(); unknown(); });
|
||||
window.addEventListener('pageshow', () => { socket?.connect(); });
|
||||
return {
|
||||
connect(auth: GameSessionAuth) {
|
||||
if (socket && sessionId === auth.gameSessionId) { socket.connect(); return; }
|
||||
socket?.removeAllListeners(); socket?.disconnect(); unknown();
|
||||
sessionId = auth.gameSessionId;
|
||||
socket = io('/presence', { auth: { gameSessionId: auth.gameSessionId, token: auth.token }, forceNew: true, autoConnect: false });
|
||||
socket.on('presence:count', (count: unknown) => {
|
||||
if (Number.isSafeInteger(count) && (count as number) >= 0) counter.textContent = `접속 ${count}명`;
|
||||
});
|
||||
socket.on('disconnect', unknown); socket.on('connect_error', unknown);
|
||||
socket.connect();
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user