Compare commits

...

4 Commits

Author SHA1 Message Date
data
654f534646 send and show messages per namespace 2019-07-24 17:21:08 +01:00
data
a119cf0c6a show user channels 2019-07-23 20:05:05 +01:00
data
e325a13156 join, send_users (#1) 2019-07-23 20:00:51 +01:00
4c63be54ea added namespaces 2019-07-23 19:53:21 +01:00
2 changed files with 115 additions and 109 deletions

View File

@ -1,65 +1,50 @@
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', () => {
socket.emit('get my rooms', socket.rooms) sendUsers()
sendNamespaces()
}) })
socket.on('message', message => { socket.on('message', message => {
io.to(message.room).emit(message) console.log('sending message to namespace', message.namespace, 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')
console.log(Object.keys(io.sockets.sockets)) sendUsers()
}) })
socket.on('get all rooms', () => { socket.on('join', namespace => {
console.log('get all rooms') console.log('join:', namespace)
console.log( socket.join(namespace, () => {
Object.keys(io.sockets.adapter.rooms) sendNamespaces()
.filter(r => r[0] === '#')
.map(k => ({
roomName: k,
sockets: Object.keys(io.sockets.adapter.rooms[k]['sockets']),
}))
)
})
socket.on('get my rooms', () => {
console.log('get my rooms')
console.log(Object.keys(socket.rooms))
})
socket.on('join a room', roomName => {
console.log('join a room')
socket.join(roomName, () => {
socket.emit('get my rooms')
}) })
}) })
socket.on('leave a room', () => { socket.on('part', () => {
console.log('leave a room') console.log('part')
}) })
socket.on('join', payload => { socket.on('get namespaces', () => sendNamespaces())
console.log(payload.room)
socket.join({ room: payload.room }, () => { const sendNamespaces = () => {
socket.emit('got user rooms', Object.keys(socket.rooms)) 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 = () =>
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.`)
io.emit( sendNamespaces()
'received rooms', sendUsers()
Object.keys(io.sockets.adapter.rooms)
.filter(r => r[0] === '#')
.map(k => ({
roomName: k,
sockets: Object.keys(io.sockets.adapter.rooms[k]['sockets']),
}))
)
}) })
}) })
} }

View File

@ -1,7 +1,7 @@
import React from 'react' import React from 'react'
import socket from './socket' import socket from './socket'
import { Navbar, Nav, Dropdown, DropdownButton, Button } from 'react-bootstrap' import { Navbar, Nav, Dropdown, Button } from 'react-bootstrap'
import uuid from 'uuid' import uuid from 'uuid'
import moment from 'moment' import moment from 'moment'
@ -9,10 +9,9 @@ const initialState = {
loading: true, loading: true,
messages: [], messages: [],
message: '', message: '',
allRooms: [], namespaces: [],
myRooms: [], namespace: '/',
room: '/', allUsers: [],
users: [],
user: {}, user: {},
} }
@ -23,7 +22,7 @@ class App extends React.Component {
this.socket = socket this.socket = socket
this.handleChange = this.handleChange.bind(this) this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this) this.handleSubmit = this.handleSubmit.bind(this)
this.joinRoom = this.joinRoom.bind(this) this.join = this.join.bind(this)
} }
async fetchData() { async fetchData() {
@ -32,9 +31,10 @@ class App extends React.Component {
componentDidMount() { componentDidMount() {
this.fetchData() this.fetchData()
this.socket.on('message', msg => { this.socket.on('connect', () => {
const messages = this.state.messages.concat(msg) console.log('connected!')
this.setState({ messages }) const user = { socketId: this.socket.id }
this.setState({ user })
}) })
this.socket.on('user connected', payload => { this.socket.on('user connected', payload => {
@ -45,14 +45,19 @@ class App extends React.Component {
console.log('a user disconnected.', payload) console.log('a user disconnected.', payload)
}) })
this.socket.on('received rooms', rooms => { this.socket.on('got namespaces', namespaces => {
console.log(rooms) console.log('got namespaces:', namespaces)
this.setState({ rooms }) this.setState({ namespaces })
}) })
this.socket.on('get user rooms', roomArray => { this.socket.on('got users', allUsers => {
const myRooms = roomArray.filter(roomString => roomString[0] === '#') console.log('got users:', allUsers)
this.setState({ myRooms }) this.setState({ allUsers })
})
this.socket.on('message', msg => {
const messages = this.state.messages.concat(msg)
this.setState({ messages })
}) })
} }
@ -60,15 +65,26 @@ class App extends React.Component {
this.setState({ [e.target.name]: e.target.value }) this.setState({ [e.target.name]: e.target.value })
} }
parseCommand() {
const args = this.state.message.split(' ')
const cmd = args[0].slice(1)
console.log('command:', cmd)
if (cmd === 'join') this.join(args[1])
this.setState({ message: '' })
}
handleSubmit(e) { handleSubmit(e) {
e.preventDefault() e.preventDefault()
if (this.state.message[0] === '/') return this.parseCommand()
const message = { const message = {
id: uuid(), id: uuid(),
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,
} }
this.sendMessage(message) this.sendMessage(message)
this.setState({ message: '' }) this.setState({ message: '' })
} }
@ -79,13 +95,22 @@ class App extends React.Component {
renderError() { renderError() {
return <div>something went wrong.</div> return <div>something went wrong.</div>
} }
joinRoom(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*/}
@ -95,55 +120,35 @@ 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.users.map(r => ( {this.state.allUsers.map(u => (
<Dropdown.Item className="bg-dark text-light"> <Dropdown.Item key={u} className="bg-dark text-light">
{r.roomName} {u}
</Dropdown.Item> </Dropdown.Item>
))} ))}
</Dropdown.Menu> </Dropdown.Menu>
</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 className="bg-dark text-light"> <Dropdown.Item
{r.roomName} key={r.namespace}
className="bg-dark text-light"
onClick={() => this.join(r.namespace)}
>
{r.namespace}
</Dropdown.Item> </Dropdown.Item>
))} ))}
</Dropdown.Menu> </Dropdown.Menu>
</Dropdown> </Dropdown>
</Nav> </Nav>
<Button
variant="dark"
onClick={() => {
this.socket.emit('get all users')
}}
>
Get All Users
</Button>
<Button
variant="dark"
onClick={() => {
this.socket.emit('get all rooms')
}}
>
Get All Rooms
</Button>
<Button
variant="dark"
onClick={() => {
this.socket.emit('get my rooms')
}}
>
Get My Rooms
</Button>
</Navbar.Collapse> </Navbar.Collapse>
</Navbar> </Navbar>
@ -154,30 +159,46 @@ 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>
<p>this currently shows all channels</p>
{this.state.myRooms.map(r => ( <Button
<button key="/"
key={r.roomName} className="btn btn-dark d-flex"
className="btn btn-dark d-flex" onClick={() => this.setState({ namespace: '/' })}
onClick={() => this.joinRoom(r.roomName)} >
> <div className="mr-auto">server</div>
<div className="mr-auto">{r.roomName}</div> {/*<div className="ml-auto">{this.state.allUsers.length}</div>*/}
<div className="ml-auto">{r.sockets.length}</div> </Button>
</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>
</Button>
))}
</div> </div>
{/*Main Section*/} {/*Main Section*/}
<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">current channel</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 {this.state.messages
.filter(m => m.room === this.state.room) .filter(m => m.namespace === this.state.namespace)
.map(m => ( .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>
@ -194,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>