62 lines
1.6 KiB
JavaScript
62 lines
1.6 KiB
JavaScript
const users = {}
|
|
|
|
module.exports = io => {
|
|
io.on('connection', async socket => {
|
|
console.log(`A socket connection to the server has been made: ${socket.id}`)
|
|
users[socket.id] = { socketId: socket.id, nick: 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', (from, to) => io.to(to).emit('chat', from))
|
|
|
|
socket.on('part', () => {
|
|
console.log('part')
|
|
})
|
|
socket.on('change nick', (socketId, nick) => {
|
|
users[socketId]['nick'] = nick
|
|
})
|
|
|
|
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 = () =>
|
|
io.emit(
|
|
'got users',
|
|
Object.keys(io.sockets.sockets).map(socketId => users[socketId])
|
|
)
|
|
|
|
socket.on('disconnect', async () => {
|
|
io.emit('user disconnected', { socketId: socket.id })
|
|
console.log(`${socket.id} has disconnected.`)
|
|
sendNamespaces()
|
|
sendUsers()
|
|
})
|
|
})
|
|
}
|