Skip to content

Commit

Permalink
show # of online users
Browse files Browse the repository at this point in the history
  • Loading branch information
JacobDChamberlain committed Jan 4, 2025
1 parent 0244802 commit 9d9d8be
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
2 changes: 2 additions & 0 deletions backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ io.on('connection', (socket) => {
connectedUsers[socket.id] = userId;

console.log(`User connected: ${userId}`);
io.emit('onlineUsers', Object.keys(connectedUsers).length); // Broadcast the user count

socket.on('message', (msg) => {
// Broadcast the message with the sender's ID
Expand All @@ -56,6 +57,7 @@ io.on('connection', (socket) => {
socket.on('disconnect', () => {
console.log(`User disconnected: ${connectedUsers[socket.id]}`);
delete connectedUsers[socket.id];
io.emit('onlineUsers', Object.keys(connectedUsers).length); // Broadcast the updated user count
});
});

Expand Down
12 changes: 10 additions & 2 deletions frontend/src/components/Pages/Chat/Chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ function Chat() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const [myUserId, setMyUserId] = useState(null);
const [onlineUsers, setOnlineUsers] = useState(0); // Track the number of online users
const userColors = useRef({}); // Persistent mapping for user colors

const getUserColor = (userId) => {
Expand All @@ -27,7 +28,6 @@ function Chat() {
return userColors.current[userId];
};


useEffect(() => {
// Connect to WebSocket and set up listeners
socket.on('connect', () => {
Expand All @@ -38,9 +38,14 @@ function Chat() {
setMessages((prevMessages) => [...prevMessages, { userId, msg }]);
});

socket.on('onlineUsers', (count) => {
setOnlineUsers(count); // Update the online users count
});

return () => {
socket.off('connect');
socket.off('message');
socket.off('onlineUsers');
};
}, []);

Expand Down Expand Up @@ -77,7 +82,10 @@ function Chat() {
}}
>
<h2 style={{ color: '#fff', textAlign: 'center' }}>Sup, Fool?</h2>
<h4 style={{ color: '#fff', textAlign: 'center', marginBottom: '20px' }}>You wanna talk some shit?</h4>
<h4 style={{ color: '#fff', textAlign: 'center', marginBottom: '10px' }}>You wanna talk some shit?</h4>
<p style={{ color: '#fff', textAlign: 'center', marginBottom: '20px' }}>
Users online: <strong>{onlineUsers}</strong>
</p>
<div
style={{
maxHeight: '300px',
Expand Down

0 comments on commit 9d9d8be

Please sign in to comment.