Last active
August 30, 2024 00:40
-
-
Save naoki-sawada/2f4e135feb3c6bad7f555f59dfb40020 to your computer and use it in GitHub Desktop.
Simple socket.io room and auth example
This file contains 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 io = require('socket.io-client'); | |
const socket = io('http://localhost:3000', { | |
transportOptions: { | |
polling: { | |
extraHeaders: { | |
'Authorization': 'Bearer abc', | |
}, | |
}, | |
}, | |
}); | |
socket.on('connect', () => { | |
console.log('connected!'); | |
socket.emit('room', 'room1'); | |
}); | |
socket.on('message', data => { | |
console.log(data); | |
}); |
This file contains 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 server = require('http').createServer(); | |
const io = require('socket.io')(server); | |
const isValidJwt = (header) => { | |
const token = header.split(' ')[1]; | |
if (token === 'abc') { | |
return true; | |
} else { | |
return false; | |
} | |
}; | |
// io.of('/test'); | |
io.use((socket, next) => { | |
const header = socket.handshake.headers['authorization']; | |
console.log(header); | |
if (isValidJwt(header)) { | |
return next(); | |
} | |
return next(new Error('authentication error')); | |
}); | |
io.on('connection', (socket) => { | |
socket.on('room', room => { | |
console.log(room); | |
socket.join(room); | |
}); | |
}); | |
setInterval(() => { | |
io.sockets.to('room1').emit('message', 'what is going on, party people?'); | |
}, 3000); | |
setInterval(() => { | |
io.sockets.to('room2').emit('message', 'anyone in this room yet?'); | |
}, 3000); | |
server.listen(3000); |
neody
commented
Dec 22, 2021
Fantastic, short, clean and simple. More importat: works
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment