forked from notnull/ircz
backend - namespace => room - add listener 'get all clients' frontend - remove variables from initalState - create components Sidebar, TopBar, Messages, MessageEntryForm
65 lines
1.9 KiB
JavaScript
65 lines
1.9 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 }
|
|
|
|
// announce to all
|
|
socket.broadcast.emit('user connected', users[socket.id])
|
|
// send all users TODO remove
|
|
socket.emit(
|
|
'got users',
|
|
Object.keys(io.sockets.sockets).map(socketId => users[socketId])
|
|
)
|
|
|
|
socket.on('message', message => {
|
|
console.log('sending message to ', message.to, message)
|
|
io.to(message.to).emit('message', message)
|
|
})
|
|
|
|
socket.on('join', room => {
|
|
console.log(`${socket.id} joins ${room}`)
|
|
socket.join(room, () => {
|
|
io.to(room).emit('user joined', { room, socketId: socket.id })
|
|
io.of(room).clients((error, clients) => {
|
|
if (error) throw error
|
|
socket.emit('got client list', clients)
|
|
})
|
|
})
|
|
})
|
|
socket.on('get all clients', () => {
|
|
io.clients((e, c) => {
|
|
if (e) console.log(e)
|
|
console.log('all clients:', c)
|
|
})
|
|
})
|
|
socket.on('part', namespace => {
|
|
console.log('part', socket.id, namespace)
|
|
io.to(namespace).emit('user left', { namespace, socketId: socket.id })
|
|
socket.leave(namespace)
|
|
})
|
|
|
|
socket.on('change nick', nick => {
|
|
io.emit('changed nick', { socketId: socket.id, nick: nick })
|
|
users[socket.id]['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)
|
|
}
|
|
|
|
socket.on('disconnect', async () => {
|
|
io.emit('user disconnected', socket.id)
|
|
console.log(`${socket.id} has disconnected.`)
|
|
//sendNamespaces()
|
|
})
|
|
})
|
|
}
|