Skip to content

Commit

Permalink
socket connect/disconnect works correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
ShadowCat567 committed Apr 24, 2024
1 parent 0b6459a commit cad7e6d
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 13 deletions.
13 changes: 6 additions & 7 deletions back-end/Server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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, () => {
Expand Down
10 changes: 5 additions & 5 deletions front-end/src/ChatPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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 () => {
Expand Down
2 changes: 1 addition & 1 deletion front-end/src/RegistrationForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit cad7e6d

Please sign in to comment.