Skip to content

Commit

Permalink
Recieving messages on all clients
Browse files Browse the repository at this point in the history
  • Loading branch information
andersholt committed May 4, 2022
1 parent f262f90 commit f666d1b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
10 changes: 6 additions & 4 deletions client/src/pages/chatapp.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,12 @@ export function ChatApplication() {
ws.onmessage = (event) => {
console.log(event.data);
const { author, message } = JSON.parse(event.data);

setChatLog([...chatLog, { author, message }]);
};
setWs(ws);
}, []);

const user = useContext(ProfileContext).userinfo.name;
const userName = useContext(ProfileContext).userinfo.name;

const [chatLog, setChatLog] = useState([
{ author: "Anders", message: "Hello" },
Expand All @@ -36,12 +35,15 @@ export function ChatApplication() {

function handleNewMessage(event) {
event.preventDefault();
setChatLog([...chatLog, { author: user, message }]);

const chatMessage = { author: userName, message };
ws.send(JSON.stringify(chatMessage));
setMessage("");
}

return (
<>
<header>Chatapp for {user}</header>
<header>Chatapp for {userName}</header>
<main>
{chatLog.map((chat, index) => (
<ChatMessage key={index} chat={chat} />
Expand Down
9 changes: 9 additions & 0 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,18 @@ app.use((req, res, next) => {
}
});

const sockets = [];

const wsServer = new WebSocketServer({ noServer: true });
wsServer.on("connect", (socket) => {
sockets.push(socket);
socket.send(JSON.stringify({ author: "Server", message: "Hello there" }));
socket.on("message", (data) => {
const { author, message } = JSON.parse(data);
for (const recipient of sockets) {
recipient.send(JSON.stringify({ author, message }));
}
});
});

const server = app.listen(process.env.PORT || 3000, () => {
Expand Down

0 comments on commit f666d1b

Please sign in to comment.