forked from codezri/fastify-websocket-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
52 lines (45 loc) · 1.3 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const fastify = require('fastify')();
const path = require('path')
fastify.register(require('fastify-websocket'));
fastify.register(require('fastify-static'), {
root: path.join(__dirname, 'www')
})
fastify.addHook('preValidation', async (request, reply) => {
if(request.routerPath == '/chat' && !request.query.username) {
reply.code(403).send('Connection rejected');
}
})
fastify.get('/chat', { websocket: true }, (connection, req) => {
// New user
broadcast({
sender: '__server',
message: `${req.query.username} joined`
});
// Leaving user
connection.socket.on('close', () => {
broadcast({
sender: '__server',
message: `${req.query.username} left`
});
});
// Broadcast incoming message
connection.socket.on('message', (message) => {
message = JSON.parse(message.toString());
broadcast({
sender: req.query.username,
...message
});
});
});
fastify.listen({ port: 3000 }, (err, address) => {
if(err) {
console.error(err);
process.exit(1);
}
console.log(`Server listening at: ${address}`);
});
function broadcast(message) {
for(let client of fastify.websocketServer.clients) {
client.send(JSON.stringify(message));
}
}