1
0
forked from notnull/ircz
ircz/server/socket/index.js
notnull 6da52f2770 lots of refactoring
backend
- join channels on frontend
- broadcast 'user connected'
- emit 'user joined', 'user left', 'changed nick', 'user disconnected'

frontend
- handleSubmit > submitMessage
- formatMessage()
- chats on state with channels and private chats
- announce 'user connected', 'user joined', 'user left', 'changed nick'
- no longer emit 'chat'
- show nick in message window instead of socketId
2019-07-27 18:43:05 +01:00

70 lines
2.1 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', namespace => {
const socketId = socket.id
console.log(`${socketId} joins ${namespace}`)
socket.join(namespace, () => {
io.to(namespace).emit('user joined', { namespace, socketId })
sendNamespace(namespace)
})
})
socket.on('part', namespace => {
const socketId = socket.id
console.log('part', socketId, namespace)
socket.leave(namespace, () => {
io.to(namespace).emit('user left', { namespace, socketId })
sendNamespace(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()
})
const sendNamespace = namespace => {
if (!io.sockets.adapter.rooms[namespace]) return
const newNamespace = {
namespace,
sockets: Object.keys(io.sockets.adapter.rooms[namespace].sockets),
}
io.emit('got namespace', newNamespace)
}
})
}