send and show messages per namespace

This commit is contained in:
data 2019-07-23 21:24:56 +01:00
parent a119cf0c6a
commit 654f534646
2 changed files with 85 additions and 122 deletions

View File

@ -1,33 +1,25 @@
module.exports = io => { module.exports = io => {
io.on('connection', async socket => { io.on('connection', async socket => {
console.log(`A socket connection to the server has been made: ${socket.id}`) console.log(`A socket connection to the server has been made: ${socket.id}`)
socket.join('#chat', () => { socket.join('#projex', () => {
sendAllRooms() sendUsers()
sendAllUsers() sendNamespaces()
send_rooms()
send_user_rooms()
}) })
socket.on('message', message => { socket.on('message', message => {
console.log(`send a message to room ${message.room}: ${message}`) console.log('sending message to namespace', message.namespace, message)
io.of(message.room).emit('message', message) io.to(message.namespace).emit('message', message)
}) })
socket.on('get all users', () => { socket.on('get users', () => {
console.log('get all users') console.log('get users')
sendAllUsers() sendUsers()
}) })
socket.on('get my rooms', () => { socket.on('join', namespace => {
console.log('get my rooms') console.log('join:', namespace)
sendAllRooms() socket.join(namespace, () => {
}) sendNamespaces()
socket.on('join', roomName => {
console.log('join:', roomName)
socket.join(roomName, () => {
sendAllRooms()
send_user_rooms()
}) })
}) })
@ -35,57 +27,24 @@ module.exports = io => {
console.log('part') console.log('part')
}) })
socket.on('get all rooms', () => sendAllRooms()) socket.on('get namespaces', () => sendNamespaces())
socket.on('join', payload => {
console.log(payload.room)
socket.join(payload.room, () => {
socket.emit('got user rooms', Object.keys(socket.rooms))
send_rooms()
send_user_rooms()
})
})
const sendAllRooms = () => { const sendNamespaces = () => {
console.log('get all rooms') const namespaces = Object.keys(io.sockets.adapter.rooms).map(k => ({
const allRooms = Object.keys(io.sockets.adapter.rooms) namespace: k,
.filter(r => r[0] === '#')
.map(k => ({
roomName: k,
sockets: Object.keys(io.sockets.adapter.rooms[k]['sockets']), sockets: Object.keys(io.sockets.adapter.rooms[k]['sockets']),
})) }))
io.emit('got all rooms', allRooms) io.emit('got namespaces', namespaces)
} }
const sendAllUsers = () => const sendUsers = () =>
socket.emit('got all users', Object.keys(io.sockets.sockets)) socket.emit('got users', Object.keys(io.sockets.sockets))
socket.on('disconnect', async () => { socket.on('disconnect', async () => {
io.emit('user disconnected', { socketId: socket.id }) io.emit('user disconnected', { socketId: socket.id })
console.log(`${socket.id} has disconnected.`) console.log(`${socket.id} has disconnected.`)
send_rooms() sendNamespaces()
sendUsers()
}) })
io.emit('received users', Object.keys(io.sockets.sockets))
function send_rooms() {
io.emit(
'received rooms',
Object.keys(io.sockets.adapter.rooms)
.filter(r => r[0] === '#')
.map(k => ({
roomName: k,
sockets: Object.keys(io.sockets.adapter.rooms[k]['sockets']),
}))
)
}
function send_user_rooms() {
console.log(socket.rooms)
socket.emit(
'received my rooms',
Object.keys(io.sockets.adapter.rooms).map(k => ({
roomName: k,
sockets: io.sockets.adapter.rooms[k]['sockets'],
}))
)
}
}) })
} }

View File

@ -9,8 +9,8 @@ const initialState = {
loading: true, loading: true,
messages: [], messages: [],
message: '', message: '',
allRooms: [], namespaces: [],
room: '/', namespace: '/',
allUsers: [], allUsers: [],
user: {}, user: {},
} }
@ -27,14 +27,12 @@ class App extends React.Component {
async fetchData() { async fetchData() {
this.setState({ loading: false }) this.setState({ loading: false })
this.socket.emit('get my rooms')
} }
componentDidMount() { componentDidMount() {
this.fetchData() this.fetchData()
this.socket.on('connect', () => { this.socket.on('connect', () => {
console.log('connected!') console.log('connected!')
this.socket.emit('get all rooms')
const user = { socketId: this.socket.id } const user = { socketId: this.socket.id }
this.setState({ user }) this.setState({ user })
}) })
@ -47,13 +45,13 @@ class App extends React.Component {
console.log('a user disconnected.', payload) console.log('a user disconnected.', payload)
}) })
this.socket.on('got all rooms', allRooms => { this.socket.on('got namespaces', namespaces => {
console.log('got all rooms:', allRooms) console.log('got namespaces:', namespaces)
this.setState({ allRooms }) this.setState({ namespaces })
}) })
this.socket.on('got all users', allUsers => { this.socket.on('got users', allUsers => {
console.log('got all users:', allUsers) console.log('got users:', allUsers)
this.setState({ allUsers }) this.setState({ allUsers })
}) })
@ -61,17 +59,6 @@ class App extends React.Component {
const messages = this.state.messages.concat(msg) const messages = this.state.messages.concat(msg)
this.setState({ messages }) this.setState({ messages })
}) })
this.socket.on('received my rooms', myRooms => {
console.log('my rooms', myRooms)
this.setState({ myRooms })
})
this.socket.on('received users', users => {
console.log(users)
this.setState({ users })
})
this.socket.on('join', room => {
console.log('joining', room)
})
} }
handleChange(e) { handleChange(e) {
@ -82,7 +69,7 @@ class App extends React.Component {
const args = this.state.message.split(' ') const args = this.state.message.split(' ')
const cmd = args[0].slice(1) const cmd = args[0].slice(1)
console.log('command:', cmd) console.log('command:', cmd)
if (cmd === 'join') this.socket.emit('join', args[1]) if (cmd === 'join') this.join(args[1])
this.setState({ message: '' }) this.setState({ message: '' })
} }
handleSubmit(e) { handleSubmit(e) {
@ -95,19 +82,9 @@ class App extends React.Component {
date: moment().format('MMMM D YYYY, h:mm a'), date: moment().format('MMMM D YYYY, h:mm a'),
socketId: this.socket.id, socketId: this.socket.id,
text: this.state.message, text: this.state.message,
room: this.state.room, namespace: this.state.namespace,
}
if (message.text[0] === '/') {
// handle commands in separate function
const args = this.state.message.split(' ')
const cmd = args[0].slice(1, 5)
console.log('saw a command:', cmd)
if (cmd === 'join') {
const room = args[1]
console.log('user wants to join', room)
this.joinRoom(room)
}
} }
this.sendMessage(message) this.sendMessage(message)
this.setState({ message: '' }) this.setState({ message: '' })
} }
@ -118,13 +95,22 @@ class App extends React.Component {
renderError() { renderError() {
return <div>something went wrong.</div> return <div>something went wrong.</div>
} }
join(room) { join(namespace) {
this.socket.emit('join', room) if (namespace.slice(0, 1) !== '#') return alert('Use a leading #, silly!')
console.log('joining', namespace)
this.socket.emit('join', namespace)
this.setState({ namespace })
} }
sendMessage(msg) { sendMessage(msg) {
this.socket.emit('message', msg) this.socket.emit('message', msg)
} }
renderApp() { renderApp() {
const title =
this.state.namespace[0] === '#'
? 'Channel'
: this.state.namespace[0] === '/'
? 'server messages'
: 'User'
return ( return (
<main role="main" className="d-flex h-100 flex-column"> <main role="main" className="d-flex h-100 flex-column">
{/*Navbar*/} {/*Navbar*/}
@ -134,12 +120,12 @@ class App extends React.Component {
<Nav className="ml-auto mr-3"> <Nav className="ml-auto mr-3">
<Dropdown> <Dropdown>
<Dropdown.Toggle variant="dark" id="dropdown-basic"> <Dropdown.Toggle variant="dark" id="dropdown-basic">
All Users Users
</Dropdown.Toggle> </Dropdown.Toggle>
<Dropdown.Menu className="bg-dark"> <Dropdown.Menu className="bg-dark">
{this.state.allUsers.map(u => ( {this.state.allUsers.map(u => (
<Dropdown.Item className="bg-dark text-light"> <Dropdown.Item key={u} className="bg-dark text-light">
{u} {u}
</Dropdown.Item> </Dropdown.Item>
))} ))}
@ -147,16 +133,17 @@ class App extends React.Component {
</Dropdown> </Dropdown>
<Dropdown> <Dropdown>
<Dropdown.Toggle variant="dark" id="dropdown-basic"> <Dropdown.Toggle variant="dark" id="dropdown-basic">
All Channels Channels
</Dropdown.Toggle> </Dropdown.Toggle>
<Dropdown.Menu className="bg-dark"> <Dropdown.Menu className="bg-dark">
{this.state.allRooms.map(r => ( {this.state.namespaces.map(r => (
<Dropdown.Item <Dropdown.Item
key={r.namespace}
className="bg-dark text-light" className="bg-dark text-light"
onClick={() => this.joinRoom(r.roomName)} onClick={() => this.join(r.namespace)}
> >
{r.roomName} {r.namespace}
</Dropdown.Item> </Dropdown.Item>
))} ))}
</Dropdown.Menu> </Dropdown.Menu>
@ -172,17 +159,30 @@ class App extends React.Component {
id="sidebar2" id="sidebar2"
> >
<h5 className=" border-bottom pb-2">User Channels</h5> <h5 className=" border-bottom pb-2">User Channels</h5>
{this.state.allRooms
.filter(r => r.sockets.includes(this.state.user.socketId)) <Button
.map(r => ( key="/"
<button
key={r.roomName}
className="btn btn-dark d-flex" className="btn btn-dark d-flex"
onClick={() => this.setState({ room: r.roomName })} onClick={() => this.setState({ namespace: '/' })}
> >
<div className="mr-auto">{r.roomName}</div> <div className="mr-auto">server</div>
{/*<div className="ml-auto">{this.state.allUsers.length}</div>*/}
</Button>
{this.state.namespaces
.filter(
r =>
r.namespace[0] === '#' &&
r.sockets.includes(this.state.user.socketId)
)
.map(r => (
<Button
key={r.namespace}
className="btn btn-dark d-flex"
onClick={() => this.setState({ namespace: r.namespace })}
>
<div className="mr-auto">{r.namespace}</div>
<div className="ml-auto">{r.sockets.length}</div> <div className="ml-auto">{r.sockets.length}</div>
</button> </Button>
))} ))}
</div> </div>
@ -190,12 +190,16 @@ class App extends React.Component {
<div className="bg-secondary d-flex flex-column flex-grow-1 px-2 pb-4"> <div className="bg-secondary d-flex flex-column flex-grow-1 px-2 pb-4">
{/*Main Section Header*/} {/*Main Section Header*/}
<div className="d-flex justify-content-between flex-wrap flex-md-nowrap pt-3 pb-2 mb-3 border-bottom"> <div className="d-flex justify-content-between flex-wrap flex-md-nowrap pt-3 pb-2 mb-3 border-bottom">
<h4 className="mr-auto ml-3">Channel: {this.state.room}</h4> <h4 className="mr-auto ml-3">
{title}: {this.state.namespace}
</h4>
</div> </div>
{/*Main Section Content*/} {/*Main Section Content*/}
<div className="d-flex flex-column border border-secondary flex-grow-1"> <div className="d-flex flex-column border border-secondary flex-grow-1">
<div className="bg-dark flex-grow-1 p-2 text-light"> <div className="bg-dark flex-grow-1 p-2 text-light">
{this.state.messages.map(m => ( {this.state.messages
.filter(m => m.namespace === this.state.namespace)
.map(m => (
<div className="d-flex justify-content-between" key={m.id}> <div className="d-flex justify-content-between" key={m.id}>
<div>{m.date}</div> <div>{m.date}</div>
<div>{m.socketId}</div> <div>{m.socketId}</div>
@ -211,13 +215,13 @@ class App extends React.Component {
placeholder="Enter message" placeholder="Enter message"
onChange={this.handleChange} onChange={this.handleChange}
/> />
<button <Button
className="btn btn-dark" className="btn btn-dark"
type="submit" type="submit"
onSubmit={this.handleSubmit} onSubmit={this.handleSubmit}
> >
submit submit
</button> </Button>
</form> </form>
</div> </div>
</div> </div>