Skip to content

Instantly share code, notes, and snippets.

@naoki-sawada
Last active August 30, 2024 00:40
Show Gist options
  • Save naoki-sawada/2f4e135feb3c6bad7f555f59dfb40020 to your computer and use it in GitHub Desktop.
Save naoki-sawada/2f4e135feb3c6bad7f555f59dfb40020 to your computer and use it in GitHub Desktop.
Simple socket.io room and auth example
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);
});
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
Copy link

neody commented Dec 22, 2021

console.log('shark eats seafood');
console.log('Thank you fery mut');

@markosole
Copy link

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