Skip to content

Commit cc9771b

Browse files
committed
Added Socket event class
1 parent 7641c6f commit cc9771b

File tree

2 files changed

+42
-26
lines changed

2 files changed

+42
-26
lines changed

app/config/socket.ts

Lines changed: 39 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,42 @@
1+
import { AuthUtil } from "../utils/auth.util";
2+
13
const 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+
}

server.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ import * as express from 'express';
22
import { ClusterConfig } from './cluster';
33
const port = 3001;
44
const app: express.Application = require('./app/app');
5-
import { socketInit } from './app/config/socket';
5+
import { Socket } from './app/config/socket';
66

77
const clusterConfig = new ClusterConfig();
88

99
clusterConfig.initaliseCLuster(false, (isReady: boolean) => {
1010
const server = app.listen(port, () => {
1111
console.log("Node app is running at localhost:" + port);
1212
});
13-
socketInit(server);
13+
const socket = new Socket();
14+
socket.init(server);
1415
});

0 commit comments

Comments
 (0)