Skip to content

Instantly share code, notes, and snippets.

@annibuliful
Created June 27, 2019 07:14
Show Gist options
  • Select an option

  • Save annibuliful/c6b2064c330a98e9d13a1de04ddfbde8 to your computer and use it in GitHub Desktop.

Select an option

Save annibuliful/c6b2064c330a98e9d13a1de04ddfbde8 to your computer and use it in GitHub Desktop.
const fastify = require('fastify')();
const Websocket = require('ws');
const wsServer = new Websocket.Server({
port:3000,
server: fastify.server
});
fastify.decorate('ws',wsServer);
fastify.ready((err)=>{
if(err) throw Error(err);
fastify.ws.on('connection',(socket)=>{
socket.room = []
socket.on('message',(message)=>{
const data = JSON.parse(message);
if(data.operation === 'join'){
socket.room.push(data.roomId);
}else if(data.operation === 'send'){
wsServer.clients.forEach((client)=>{
if( client.readyState === 1 &&
client.room.indexOf(data.roomId) !== -1){
client.send(data.message);
}
})
}
})
socket.send("wwww");
})
})
fastify.listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment