Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrated backend for WebSocket and half-way done with frontend #4

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 27 additions & 5 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@
"express": "^4.21.1",
"jsonwebtoken": "^9.0.2",
"mailtrap": "^3.4.0",
"mongoose": "^8.7.0",
"mongoose": "^8.7.2",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.27.0",
"react-toastify": "^10.0.6"
"react-toastify": "^10.0.6",
"ws": "^8.18.0"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
Expand Down
1 change: 1 addition & 0 deletions client/src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ createRoot(document.getElementById('root')).render(
</BrowserRouter>
</StrictMode>,
)

131 changes: 131 additions & 0 deletions client/src/pages/Chat.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// import React, { useState, useEffect } from 'react';
// import { useWebSocket } from './websocket_client';

// const Chat = ({ userID }) => {
// const [toUser, setToUser] = useState('');
// const [messageContent, setMessageContent] = useState('');
// const [messages, setMessages] = useState([]);
// const socket = useWebSocket();

// useEffect(() => {
// if (socket) {
// socket.onmessage = (event) => {
// const message = JSON.parse(event.data);
// if (message.error) {
// console.error("Error:", message.error);
// } else {
// setMessages((prev) => [...prev, message]);
// }
// };
// }
// }, [socket]);

// const sendMessage = () => {
// if (socket && toUser && messageContent) {
// const message = { from: userID, to: toUser, content: messageContent };
// socket.send(JSON.stringify(message));
// setMessageContent('');
// }
// };

// return (
// <div>
// <div>
// <label>To User ID:</label>
// <input
// type="text"
// value={toUser}
// onChange={(e) => setToUser(e.target.value)}
// />
// </div>
// <div>
// <label>Message:</label>
// <input
// type="text"
// value={messageContent}
// onChange={(e) => setMessageContent(e.target.value)}
// />
// <button onClick={sendMessage}>Send</button>
// </div>
// <div id="chatBox" style={{ border: '1px solid black', height: '300px', overflowY: 'scroll' }}>
// {messages.map((msg, index) => (
// <div key={index}>
// <strong>{msg.from}</strong>: {msg.content} <em>({new Date(msg.timestamp).toLocaleTimeString()})</em>
// </div>
// ))}
// </div>
// </div>
// );
// };

// export default Chat;

import React, { useState, useEffect } from 'react';

const Chat = ({ userID }) => {
const [socket, setSocket] = useState(null);
const [toUser, setToUser] = useState('');
const [messageContent, setMessageContent] = useState('');
const [messages, setMessages] = useState([]);

useEffect(() => {
// Establish WebSocket connection
const ws = new WebSocket(`ws://localhost:8080?userID=${userID}`);
setSocket(ws);

ws.onopen = () => console.log("Connected to WebSocket server");

ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.error) {
console.error("Error:", message.error);
} else {
setMessages((prev) => [...prev, message]);
}
};

ws.onclose = () => console.log("Disconnected from WebSocket server");

// Cleanup on component unmount
return () => ws.close();
}, [userID]);

const sendMessage = () => {
if (socket && toUser && messageContent) {
const message = { from: userID, to: toUser, content: messageContent };
socket.send(JSON.stringify(message));
setMessageContent('');
}
};

return (
<div>
<div>
<label>To User ID:</label>
<input
type="text"
value={toUser}
onChange={(e) => setToUser(e.target.value)}
/>
</div>
<div>
<label>Message:</label>
<input
type="text"
value={messageContent}
onChange={(e) => setMessageContent(e.target.value)}
/>
<button onClick={sendMessage}>Send</button>
</div>
<div id="chatBox" style={{ border: '1px solid black', height: '300px', overflowY: 'scroll' }}>
{messages.map((msg, index) => (
<div key={index}>
<strong>{msg.from}</strong>: {msg.content} <em>({new Date(msg.timestamp).toLocaleTimeString()})</em>
</div>
))}
</div>
</div>
);
};

export default Chat;
2 changes: 1 addition & 1 deletion client/src/pages/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ function Login() {
</div>
<button type='submit'>Login</button>
<span>Don't have an account?
<Link to="/register">Login</Link>
<Link to="/register">Sign up</Link>
</span>
</form>
<ToastContainer />
Expand Down
67 changes: 67 additions & 0 deletions client/websocket_client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// // //

// // const userID = 'user1'; // unique user ID
// // const socket = new WebSocket(`ws://localhost:8080?userID=${userID}`);

// // socket.onopen = () => {
// // console.log("Connected to the WebSocket server");
// // };

// // socket.onmessage = (event) => {
// // const message = JSON.parse(event.data);

// // if (message.error) {
// // console.error("Error:", message.error);
// // } else {
// // displayMessage(message);
// // }
// // };

// // socket.onclose = () => {
// // console.log("Disconnected from WebSocket server"); // we can also add reconnection logic if needed
// // };

// // function sendMessage(to, content) {
// // const message = { from: userID, to, content };
// // socket.send(JSON.stringify(message));
// // }

// // function displayMessage(message) {
// // const chatBox = document.getElementById('chatBox');
// // const messageElement = document.createElement('div');
// // messageElement.innerText = `[${message.from}] ${message.content} (${new Date(message.timestamp).toLocaleTimeString()})`;
// // chatBox.appendChild(messageElement);
// // }

// // // Sending a message
// // document.getElementById('sendButton').onclick = () => {
// // const toUser = document.getElementById('toUser').value;
// // const messageContent = document.getElementById('messageContent').value;
// // sendMessage(toUser, messageContent);
// // };

// import React, { createContext, useContext, useEffect, useState } from 'react';

// const WebSocketContext = createContext();

// export const WebSocketProvider = ({ userID, children }) => {
// const [socket, setSocket] = useState(null);

// useEffect(() => {
// const ws = new WebSocket(`ws://localhost:8080?userID=${userID}`);

// ws.onopen = () => console.log("Connected to WebSocket server");
// ws.onclose = () => console.log("Disconnected from WebSocket server");
// setSocket(ws);

// return () => ws.close();
// }, [userID]);

// return (
// <WebSocketContext.Provider value={socket}>
// {children}
// </WebSocketContext.Provider>
// );
// };

// export const useWebSocket = () => useContext(WebSocketContext);
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 7 additions & 7 deletions server/node_modules/.package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading