1
0
forked from notnull/ircz
ircz/server/socket/index.js
data a09d9a8b9d fix components
backend
- sendNamespaces => sendNamespace

frontend
- namespace => buffer
- activateChate takes optional chats object to set it on state
- improved message/error handling
2019-07-28 21:26:13 +01:00

87 lines
2.7 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 => {
if (!message) {
console.log('Weird. Received empty message.')
return
}
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, () => {
sendNamespace(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', room => {
console.log('part', socket.id, room)
socket.leave(room, () => {
console.log(Object.keys(io.sockets.adapter.rooms))
if (io.sockets.adapter.rooms[room]) {
Object.keys(io.sockets.adapter.rooms[room]['sockets']).map(s => {
sendNamespace(room, s)
return s
})
} else {
console.log(`room ${room} disappeared`)
}
io.to(room).emit('user left', { room, socketId: socket.id })
})
})
socket.on('change nick', nick => {
console.log(`${users[socket.id]['nick']} changed nick to ${nick}`)
socket.broadcast.emit('changed nick', { socketId: socket.id, nick: nick })
users[socket.id]['nick'] = nick
})
const sendNamespace = (room, socketId) => {
if (io.sockets.adapter.rooms[room]) {
const namespace = {
namespace: room,
sockets: Object.keys(io.sockets.adapter.rooms[room]['sockets']),
}
if (socketId) {
socket.emit('got namespace', namespace)
} else {
io.emit('got namespace', namespace)
}
}
}
socket.on('disconnect', async () => {
console.log(`${socket.id} has disconnected.`)
io.emit('user disconnected', socket.id)
// OPTIMIZE if there's an easy way to inform rooms the socket was part of
// they should be informed here
//socket.rooms.map(r => r.sockets.map(s => sendNamespace(r, s)))
})
})
}