1
+ import { Server , Socket } from 'socket.io' ;
2
+
3
+ // Your existing matching service logic
4
+ export function initializeMatchingService ( io : Server ) {
5
+ // Maintain an array to store active users seeking a match
6
+ const activeUsers : { socket : Socket ; preferences : any } [ ] = [ ] ;
7
+
8
+ io . on ( 'connection' , ( socket : Socket ) => {
9
+ console . log ( 'A user connected' ) ;
10
+
11
+ socket . on ( 'startMatching' , ( preferences : any ) => {
12
+ // Add the user to the list of active users with their preferences
13
+ activeUsers . push ( { socket, preferences } ) ;
14
+
15
+ // Attempt to find a match for the user
16
+ tryMatchForUser ( socket , preferences ) ;
17
+ } ) ;
18
+
19
+ socket . on ( 'disconnect' , ( ) => {
20
+ console . log ( 'A user disconnected' ) ;
21
+
22
+ // Remove the user from the list of active users when they disconnect
23
+ removeUserFromActiveList ( socket ) ;
24
+ } ) ;
25
+
26
+ // Other event handlers as needed
27
+ } ) ;
28
+
29
+ function tryMatchForUser ( socket : Socket , preferences : any ) {
30
+ const { difficulty, category } = preferences ;
31
+
32
+ // Iterate through active users to find a match
33
+ const matchedUser = activeUsers . find ( ( user ) => {
34
+ return (
35
+ user . socket !== socket && // Exclude the current user from matching with themselves
36
+ user . preferences . difficulty === difficulty &&
37
+ user . preferences . category === category
38
+ ) ;
39
+ } ) ;
40
+
41
+ if ( matchedUser ) {
42
+ // Remove both users from the active list
43
+ removeUserFromActiveList ( socket ) ;
44
+ removeUserFromActiveList ( matchedUser . socket ) ;
45
+
46
+ // Emit "matchFound" to both users
47
+ socket . emit ( 'matchFound' , matchedUser . preferences ) ;
48
+ matchedUser . socket . emit ( 'matchFound' , preferences ) ;
49
+ } else {
50
+ // Handle the case when no match is found for the user
51
+ // You can emit a "noMatchFound" event or handle it differently
52
+ }
53
+ }
54
+
55
+ function removeUserFromActiveList ( socket : Socket ) {
56
+ // Remove the user from the list of active users by socket ID
57
+ const index = activeUsers . findIndex ( ( user ) => user . socket === socket ) ;
58
+ if ( index !== - 1 ) {
59
+ activeUsers . splice ( index , 1 ) ;
60
+ }
61
+ }
62
+ }
0 commit comments