ircz/server/socket/index.js
2019-07-26 12:58:44 +01:00

65 lines
1.8 KiB
JavaScript

module.exports = io => {
io.on('connection', async socket => {
console.log(`A socket connection to the server has been made: ${socket.id}`)
socket.join('#projex', () => {
sendUsers()
sendNamespaces()
})
socket.on('message', message => {
console.log('sending message to namespace', message.namespace, message)
io.to(message.namespace).emit('message', message)
})
socket.on('get users', () => {
console.log('get users')
sendUsers()
})
socket.on('join', namespace => {
console.log('join:', namespace)
socket.join(namespace, () => {
sendNamespaces()
})
})
socket.on('chat', id => {
const target = io.sockets.sockets[id]
if (!target || socket.id === target.id) {
console.log('Not starting chat.', socket, target)
return
}
console.log(`${socket.id} wants to chat with ${target.id}`)
// create a shared namespace
const namespace = `${socket.id.substr(0, 5)}.${target.id.substr(0, 5)}`
socket.join(namespace)
target.join(namespace)
sendNamespaces()
})
socket.on('part', () => {
console.log('part')
})
socket.on('get namespaces', () => sendNamespaces())
const sendNamespaces = () => {
const namespaces = Object.keys(io.sockets.adapter.rooms).map(k => ({
namespace: k,
sockets: Object.keys(io.sockets.adapter.rooms[k]['sockets']),
}))
io.emit('got namespaces', namespaces)
}
const sendUsers = () =>
socket.emit('got users', Object.keys(io.sockets.sockets))
socket.on('disconnect', async () => {
io.emit('user disconnected', { socketId: socket.id })
console.log(`${socket.id} has disconnected.`)
sendNamespaces()
sendUsers()
})
})
}