FIXME Buggy send message

This commit is contained in:
Zhongheng Liu 2023-12-21 17:20:37 +02:00
commit 1fbd955652
No known key found for this signature in database
5 changed files with 37 additions and 15 deletions

10
package-lock.json generated
View file

@ -19,6 +19,7 @@
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"react-use-websocket": "^4.5.0",
"typescript": "^4.9.5", "typescript": "^4.9.5",
"web-vitals": "^2.1.4" "web-vitals": "^2.1.4"
} }
@ -14586,6 +14587,15 @@
} }
} }
}, },
"node_modules/react-use-websocket": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/react-use-websocket/-/react-use-websocket-4.5.0.tgz",
"integrity": "sha512-oxYVLWM3Lv0InCfjW7hG/Hk0hkE0P1SiLd5/I3d5x0W4riAnDUkD4VEu7qNVAqxNjBF3nU7k0jLMOetLXpwfsA==",
"peerDependencies": {
"react": ">= 18.0.0",
"react-dom": ">= 18.0.0"
}
},
"node_modules/read-cache": { "node_modules/read-cache": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",

View file

@ -14,6 +14,7 @@
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"react-use-websocket": "^4.5.0",
"typescript": "^4.9.5", "typescript": "^4.9.5",
"web-vitals": "^2.1.4" "web-vitals": "^2.1.4"
}, },

View file

@ -1,11 +1,16 @@
import React from "react"; import React from "react";
import ChatWrapper from "./Chat/Chat"; import ChatWrapper from "./Chat/Chat";
const App = (): React.ReactElement => { const App = (): React.ReactElement => {
var username: string | null = prompt("Username: ")
if (!username) {
alert("Invalid username!")
var username: string | null = prompt("Username: ")
}
return ( return (
<div className="App"> <div className="App">
<h1>Local Area Network Chat Application</h1> <h1>Local Area Network Chat Application</h1>
<pre>This web application was built for the purposes of an EPQ project.</pre> <pre>This web application was built for the purposes of an EPQ project.</pre>
<ChatWrapper user="testuser" brokerURL=""/> <ChatWrapper user={username as string} brokerURL=""/>
</div> </div>
) )
} }

View file

@ -2,9 +2,8 @@ import React, { useState } from "react";
import { Message } from "./Message"; import { Message } from "./Message";
import { Client, Stomp } from "@stomp/stompjs"; import { Client, Stomp } from "@stomp/stompjs";
import { MessageType } from "./types"; import { MessageType } from "./types";
const domain = "localhost" import useWebSocket from "react-use-websocket";
const port = "8080"
const connectionAddress = `ws://${domain}:${port}/ws`
const ChatWrapper = ( const ChatWrapper = (
{ {
user, user,
@ -15,6 +14,9 @@ const ChatWrapper = (
brokerURL: string, brokerURL: string,
} }
): React.ReactElement => { ): React.ReactElement => {
const domain = "localhost"
const port = "8080"
const connectionAddress = `ws://${domain}:${port}/ws`
const stompClient = new Client({ const stompClient = new Client({
brokerURL: connectionAddress brokerURL: connectionAddress
}) })
@ -22,13 +24,14 @@ const ChatWrapper = (
const [connected, setConnected] = useState(false) const [connected, setConnected] = useState(false)
const [subscribe, setSubscribe] = useState("/sub/chat") const [subscribe, setSubscribe] = useState("/sub/chat")
const [username, setUsername] = useState<string>(user) const [username, setUsername] = useState<string>(user)
const [children, setChildren] = useState<React.ReactElement[]>([]) const [children, setChildren] = useState<React.ReactElement>()
stompClient.onConnect = (frame) => { stompClient.onConnect = (frame) => {
setConnected(true); setConnected(true);
stompClient.subscribe(subscribe, (message) => { stompClient.subscribe(subscribe, (message) => {
console.log(`Collected new message: ${message.body}`);
const {from, to, content} = JSON.parse(message.body) as MessageType const {from, to, content} = JSON.parse(message.body) as MessageType
const messageElement = <Message sender={from} text={content} /> const messageElement = <Message sender={from} text={content} />
children.push(messageElement) setChildren(messageElement)
}) })
} }
stompClient.onWebSocketError = (error) => { stompClient.onWebSocketError = (error) => {
@ -39,7 +42,6 @@ const ChatWrapper = (
console.error('Broker reported error: ' + frame.headers['message']); console.error('Broker reported error: ' + frame.headers['message']);
console.error('Additional details: ' + frame.body); console.error('Additional details: ' + frame.body);
}; };
const sendDataButtonHandler = (ev: React.MouseEvent) => { const sendDataButtonHandler = (ev: React.MouseEvent) => {
console.log("WebSockets handler invoked.") console.log("WebSockets handler invoked.")
ev.preventDefault() ev.preventDefault()
@ -50,10 +52,14 @@ const ChatWrapper = (
to: "everyone", to: "everyone",
content: entryElement.value content: entryElement.value
} }
stompClient.publish({ console.log(`STOMP connection status: ${stompClient.connected}`);
body: JSON.stringify(messageData),
destination: destination if (stompClient.connected) {
}) stompClient.publish({
body: JSON.stringify(messageData),
destination: destination
})
} else {alert("STOMP not activated!")}
} }
const connect = () => { const connect = () => {
stompClient.activate() stompClient.activate()
@ -84,9 +90,9 @@ const ChatWrapper = (
// }) // })
return ( return (
<div className="chat"> <div className="chat">
<button onClick={ev => connect()}>Connect</button> <button onClick={ev => connect()} disabled={false}>Connect</button>
<button onClick={ev => disconnect()}>Disconnect</button> <button onClick={ev => disconnect()} disabled={!connected}>Disconnect</button>
<div className="chat-inner"> <div id="chat-inner">
{children} {children}
</div> </div>
<span><input id="data-entry"></input><button onClick={ev => sendDataButtonHandler(ev)}>Send</button></span> <span><input id="data-entry"></input><button onClick={ev => sendDataButtonHandler(ev)}>Send</button></span>

View file

@ -9,5 +9,5 @@ export const Message = (
} }
): React.ReactElement<{ sender: string; text: string; }> => { ): React.ReactElement<{ sender: string; text: string; }> => {
return (<p>Message from {sender}: {text}</p>); return (<p>Message from {sender} @ {}: {text}</p>);
}; };