Skip to content

Commit

Permalink
feat: sid tracking across connections and disconnections
Browse files Browse the repository at this point in the history
  • Loading branch information
azaleacolburn committed Dec 3, 2024
1 parent cf00b30 commit 00c32ca
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 11 deletions.
5 changes: 4 additions & 1 deletion src/routes/admin/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
<script lang="ts">
import { browser } from '$app/environment';
import { io, Socket } from 'socket.io-client';
const session_id = browser && localStorage.getItem('session_id');
let scout_queue: string[] = $state([]);
let robot_queue: string[] = $state([]);
let socket: Socket = io({
auth: {
token: 'celary'
token: 'celary',
username: 'admin'
}
});
Expand Down
8 changes: 4 additions & 4 deletions src/routes/queue/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@
import { browser } from '$app/environment';
import { goto } from '$app/navigation';
import { io, Socket } from 'socket.io-client';
const session_id = browser && (localStorage.getItem('session_id') ?? '');
const username = 'test_scout';
let socket: Socket;
socket = io({
auth: {
session_id,
username
}
});
Expand All @@ -21,8 +19,10 @@
goto(`/scout/${match_key}-${team_key}-${color}`);
});
socket.on('you_left_queue', () => {
goto('/');
socket.on('scout_left_queue', (scout: string) => {
if (scout === username) {
goto('/');
}
});
const leave = () => {
Expand Down
18 changes: 12 additions & 6 deletions ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,20 @@ const webSocketServer = {
const io = new Server(server.httpServer);

io.use((socket, next) => {
const session_id = socket.handshake.auth.session_id;

const username = socket.handshake.auth.username;
if (!username) {
return next(new Error('invalid username'));
}
if (session_id) sid_to_username.set(session_id, username);
// create new session

let old_entries = sid_to_username.entries().find(([_key, value]) => value == username);
if (old_entries) {
old_entries
.map(([key, _value]) => key)
.forEach((key) => sid_to_username.delete(key));
}

sid_to_username.set(socket.id, username);

next();
});

Expand Down Expand Up @@ -55,9 +61,9 @@ const webSocketServer = {
.toArray()[0];
console.log(scout_sid);
// This event exist in the cast that the scout removed itself from the queue
io.to('admin_room').emit('scout_left_queue', scout_id);
io.emit('scout_left_queue', scout_id);
// This event exists in the case that the admin removed the scout from the queue
io.to(scout_sid).emit('you_left_queue');
// io.to(scout_sid).emit('you_left_queue');
io.sockets.sockets.get(scout_sid)?.leave('scout_queue');
});

Expand Down

0 comments on commit 00c32ca

Please sign in to comment.