From 9fd8ac7969af47bda58480b415870f04495db2ba Mon Sep 17 00:00:00 2001 From: data Date: Thu, 25 Jul 2019 20:03:31 +0100 Subject: [PATCH] create private namespaces --- server/socket/index.js | 14 ++++++++++++++ src/App.js | 41 +++++++++++++++++++++++++++-------------- 2 files changed, 41 insertions(+), 14 deletions(-) diff --git a/server/socket/index.js b/server/socket/index.js index ff42423..ccba873 100644 --- a/server/socket/index.js +++ b/server/socket/index.js @@ -22,6 +22,20 @@ module.exports = io => { sendNamespaces() }) }) + socket.on('chat', id => { + const target = io.sockets.sockets[id] + if (!target || socket.id === target.id) { + console.log('Not starting chat.', socket, target) + return + } + console.log(`${socket.id} wants to chat with ${target.id}`) + + // create a shared namespace + const namespace = `${socket.id.substr(0, 5)}.${target.id.substr(0, 5)}` + socket.join(namespace) + target.join(namespace) + sendNamespaces() + }) socket.on('part', () => { console.log('part') diff --git a/src/App.js b/src/App.js index c2db308..6261903 100644 --- a/src/App.js +++ b/src/App.js @@ -106,6 +106,11 @@ class App extends React.Component { this.socket.emit('join', namespace) this.setState({ namespace }) } + query(user) { + console.log(`starting query with ${user}`) + this.socket.emit('chat', user) + this.setState({ namespace: user }) + } sendMessage(msg) { this.socket.emit('message', msg) } @@ -152,11 +157,17 @@ class App extends React.Component { - {this.state.allUsers.map(u => ( - - {u} - - ))} + {this.state.allUsers + .filter(u => u !== socket.id) + .map(u => ( + this.query(u)} + > + {u} + + ))} @@ -165,15 +176,17 @@ class App extends React.Component { - {this.state.namespaces.map(r => ( - this.join(r.namespace)} - > - {r.namespace} - - ))} + {this.state.namespaces + .filter(n => n.namespace[0] === '#') + .map(r => ( + this.join(r.namespace)} + > + {r.namespace} + + ))}