1+ import { AuthUtil } from "../utils/auth.util" ;
2+
13const io = require ( 'socket.io' ) ( ) ;
2- export const Socket : any = { } ;
3- export const socketInit = ( server ) => {
4- Socket . io = io . listen ( server , {
5- log : true
6- } ) ;
7- Socket . io . use ( function ( socket , next ) {
8- console . log ( socket . handshake . query , 'socket.handshake.query' ) ;
9- if ( socket . handshake . query && socket . handshake . query . token ) {
10- // Authentiation code should be here
11- next ( ) ;
12- }
13- else {
14- next ( new Error ( 'Authentication error' ) ) ;
15- }
16- } )
17- Socket . io . on ( 'connect' , socket => {
18- console . log ( 'Client Connectted' ) ;
19- socket . send ( 'Hello!' ) ;
20- } ) ;
4+ export const SocketConf : any = { } ;
5+ export class Socket {
6+ private auth : AuthUtil ;
7+ constructor ( ) {
8+ this . auth = new AuthUtil ( ) ;
9+ }
10+ init ( server ) {
11+ SocketConf . io = io . listen ( server , {
12+ log : true
13+ } ) ;
14+ this . setupEvent ( ) ;
15+ }
2116
22- Socket . io . on ( 'join' , socket => {
23- console . log ( 'Client Connectted' ) ;
24- socket . send ( 'Hello!' ) ;
25- } ) ;
26- }
17+ setupEvent ( ) {
18+ SocketConf . io . use ( ( socket , next ) => {
19+ console . log ( socket . handshake . query , 'socket.handshake.query' ) ;
20+ if ( socket . handshake . query ) {
21+ let token = this . auth . authenticate ( socket . handshake . query . token ) ;
22+ if ( token ) {
23+ next ( ) ;
24+ } else {
25+ next ( new Error ( 'Authentication error' ) ) ;
26+ }
27+ }
28+ else {
29+ next ( new Error ( 'Authentication error' ) ) ;
30+ }
31+ } )
32+ SocketConf . io . on ( 'connect' , socket => {
33+ console . log ( 'Client Connectted' ) ;
2734
35+ socket . on ( 'join' , room => {
36+ console . log ( 'Client join' , room ) ;
37+ socket . join ( room . roomName ) ;
38+ io . to ( room . roomName ) . emit ( 'New User Connected...' ) ;
39+ } ) ;
40+ } ) ;
41+ }
42+ }
0 commit comments