Created
March 17, 2025 07:15
-
-
Save bandhan-majumder/1b5dae0d1353398d7c1bb869b3bd830f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fastify = require('fastify')(); | |
fastify.register(require('fastify-websocket')); | |
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)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment