@@ -50,15 +50,21 @@ export class ChatGateway
5050
5151 async handleDisconnect ( client : Socket ) {
5252 console . log ( `Client disconnected: ${ client . id } ` ) ;
53- const roomId = await this . gameRoomService . getRoomIdByClient ( client . id ) ;
54- const token = client . handshake . auth . token . replace ( 'Bearer ' , '' ) ;
55- const decoded : any = jwt . verify ( token , process . env . JWT_SECRET ) ;
56- const userId = Number ( decoded ?. userId ) ;
53+
54+ // 1) userId를 client.data.userId 로 가져옴
55+ const userId = client . data . userId ;
56+
57+ // 2) DB에서 userId를 이용해 어느 방에 있었는지 찾기
58+ const roomId = await this . gameRoomService . getRoomIdByClient (
59+ userId . toString ( ) ,
60+ ) ;
61+
5762 if ( roomId ) {
5863 await this . gameRoomService . leaveRoom ( roomId , userId ) ;
5964 this . server . to ( roomId . toString ( ) ) . emit ( 'message' , {
6065 sender : 'System' ,
61- message : `User ${ client . id } has disconnected.` ,
66+ // 소켓 식별자는 client.id, 그러나 실제 "유저명"을 보여주려면 userId를 써도 됨
67+ message : `User ${ userId } has disconnected.` ,
6268 } ) ;
6369 }
6470 }
@@ -114,20 +120,19 @@ export class ChatGateway
114120 async handleLeaveRoom ( client : Socket , payload : { roomId : number } ) {
115121 const { roomId } = payload ;
116122
117- const token = client . handshake . auth . token . replace ( 'Bearer ' , '' ) ;
118- const decoded : any = jwt . verify ( token , process . env . JWT_SECRET ) ;
119- const userId = Number ( decoded ?. userId ) ;
123+ // const token = client.handshake.auth.token.replace('Bearer ', '');
124+ // const decoded: any = jwt.verify(token, process.env.JWT_SECRET);
125+ // const userId = Number(decoded?.userId);
126+ const userId = client . data . userId ;
127+
120128 console . log ( userId , ' want to leave' , roomId , 'room' ) ;
121129
122- try {
130+ if ( roomId ) {
123131 await this . gameRoomService . leaveRoom ( roomId , userId ) ;
124132 this . server . to ( roomId . toString ( ) ) . emit ( 'message' , {
125133 sender : 'System' ,
126- message : `User ${ userId } left the room .` ,
134+ message : `User ${ userId } has disconnected .` ,
127135 } ) ;
128- client . leave ( roomId . toString ( ) ) ;
129- } catch ( error ) {
130- client . emit ( 'error' , { message : error . message } ) ;
131136 }
132137 }
133138}
0 commit comments