From cad7e6db50a2da6f5222b7aedb7cf62e99622bd4 Mon Sep 17 00:00:00 2001 From: ShadowCat567 Date: Tue, 23 Apr 2024 21:32:17 -0400 Subject: [PATCH] socket connect/disconnect works correctly --- back-end/Server.js | 13 ++++++------- front-end/src/ChatPage.js | 10 +++++----- front-end/src/RegistrationForm.js | 2 +- 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/back-end/Server.js b/back-end/Server.js index 5b3e871..312763c 100644 --- a/back-end/Server.js +++ b/back-end/Server.js @@ -19,30 +19,29 @@ io.on('connection_error', (err) => { console.log(err); }); -io.use((socket) => { +io.use((socket, next) => { const sockUsername = socket.handshake.auth.username; if(!sockUsername) { console.log("No username received"); + next(); } socket.username = sockUsername; console.log(`Socket username: ${socket.username}`); + next(); }); io.on('connection', (socket) => { console.log(`a user has connected, user id = ${socket.id}`); - socket.on('chat_message', (msg) => { - console.log(msg) + socket.on('chat_message', (msg, otherUser) => { + console.log(`Other user: ${otherUser}`); + console.log(msg); io.emit('chat_message', msg); }); socket.on('disconnect', () => { console.log("a user has disconnected"); }); - - socket.off('disconnect', () => { - console.log("socket is off"); - }); }); httpServer.listen(3002, () => { diff --git a/front-end/src/ChatPage.js b/front-end/src/ChatPage.js index d0d6834..ba1a85f 100644 --- a/front-end/src/ChatPage.js +++ b/front-end/src/ChatPage.js @@ -9,11 +9,11 @@ import InputTxt from './sockets/InputTxt'; import { useLocation } from 'react-router-dom'; function ChatPage() { - const location = useLocation(); //for extracting username - const otherperson_username = location.pathname.split('/').pop(); //for extracting username + const location = useLocation(); //for extracting receiver username + const otherperson_username = location.pathname.split('/').pop(); //for extracting receiver username - const [user, setUser] = useState('') - const [chats, setChats] = useState([]); + const [user, setUser] = useState(''); //stores the sending user + const [chats, setChats] = useState([]); //stores ongoing messages const [old_messages, setOldMessages] = useState([]); // New state for storing old messages useEffect(() => { @@ -70,7 +70,7 @@ function ChatPage() { //sends the message to the backend function sendToSocket(msg) { - socket.emit('chat_message', msg); + socket.emit('chat_message', msg, otherperson_username); } const getUser = async () => { diff --git a/front-end/src/RegistrationForm.js b/front-end/src/RegistrationForm.js index 44a25d3..5babc3f 100644 --- a/front-end/src/RegistrationForm.js +++ b/front-end/src/RegistrationForm.js @@ -37,7 +37,7 @@ function RegistrationForm() { setErrorMessage(data.message || 'Failed to sign up.'); } else { //connect chat socket and register username - socket.auth.username = username; + socket.auth = { username }; socket.connect(); // On successful registration, navigate to the survey page