Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
YouTube Security VideosfreeCodeCamp.org: TimescaleDB Course – PostgreSQL for Time-Series Data(23.09.2026 um 12:30 Uhr)
Windows Tipps & SecurityAndroid 17: Rollout auf Samsung-Galaxy-Smartphones verzögert sich(23.09.2026 um 11:42 Uhr)
Unix & Linux ServerUSN-8733-2: Gzip vulnerabilities(22.09.2026 um 18:04 Uhr)
Sichere ProgrammierungHow to Build Custom PowerPoint Add-Ins for Enterprise Teams(23.09.2026 um 11:25 Uhr)
Sichere ProgrammierungSearch Google Jobs in Real-Time with Go and SerpApi 🚀(23.09.2026 um 12:13 Uhr)
Sichere ProgrammierungA Psychological State is a Coefficient Vector(23.09.2026 um 12:16 Uhr)
YouTube Security VideosfreeCodeCamp.org: TimescaleDB Course – PostgreSQL for Time-Series Data(23.09.2026 um 12:30 Uhr)
Windows Tipps & SecurityAndroid 17: Rollout auf Samsung-Galaxy-Smartphones verzögert sich(23.09.2026 um 11:42 Uhr)
Unix & Linux ServerUSN-8733-2: Gzip vulnerabilities(22.09.2026 um 18:04 Uhr)
Sichere ProgrammierungHow to Build Custom PowerPoint Add-Ins for Enterprise Teams(23.09.2026 um 11:25 Uhr)
Sichere ProgrammierungSearch Google Jobs in Real-Time with Go and SerpApi 🚀(23.09.2026 um 12:13 Uhr)
Sichere ProgrammierungA Psychological State is a Coefficient Vector(23.09.2026 um 12:16 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

Real-Time Web Application demo with WebSocket - Frontend

Introduction In this article, I will explore the frontend implementation of our real-time WebSocket application. Built with Next.js and TypeScript, the frontend serves as an interactive interface for sending and receiving real-time…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!




Introduction



In this article, I will explore the frontend implementation of our real-time WebSocket application. Built with Next.js and TypeScript, the frontend serves as an interactive interface for sending and receiving real-time messages. Let's dive into the details of how this application is structured and how the components interact to provide a seamless WebSocket experience.









Project Structure



The frontend project is organized to ensure modularity and reusability. Below is the updated directory structure:




./frontend/src
├── app
│ ├── globals.css
│ ├── layout.tsx
│ └── page.tsx
├── components
│ ├── HomePage.tsx
│ ├── message
│ │ ├── MessageInputForm.tsx
│ │ ├── MessageList.tsx
│ │ └── MessageSection.tsx
│ └── websocket
│ ├── WebSocketControls.tsx
│ ├── WebSocketSection.tsx
│ └── WebSocketStatus.tsx
└── hooks
└── useMessages.ts









Key Directories and Files





  • app/: Contains global styles and layout definitions for the application.


  • components/: Includes the primary components for messages and WebSocket handling.


  • hooks/: Contains custom hooks, such as useMessages, for managing state and logic.


  • HomePage.tsx: The central page that ties everything together.









Core Component: HomePage.tsx



HomePage.tsx is the main entry point for the WebSocket application. It integrates message and WebSocket-related components while managing the application's state and lifecycle.






Code Walkthrough






"use client";

import { useState, useRef, useEffect } from "react";
import { useMessages } from "@/hooks/useMessages";
import MessageSection from "@/components/message/MessageSection";
import WebSocketSection from "@/components/websocket/WebSocketSection";

export default function HomePage() {
const { messages, clearMessages, addMessage } = useMessages();
const [connectionStatus, setConnectionStatus] = useState<
"Connected" | "Disconnected"
>("Disconnected");
const [isSending, setIsSending] = useState<boolean>(false);
const [message, setMessage] = useState<string>("");
const wsRef = useRef<WebSocket | null>(null);

useEffect(() => {
return () => {
if (wsRef.current) {
wsRef.current.close();
}
};
}, []);

const handleOpen = () => {
console.log("Connected to WebSocket");
setConnectionStatus("Connected");
};

const handleMessage = (event: MessageEvent) => {
console.log("Message from server:", event.data);
const data = JSON.parse(event.data);
addMessage(data.message, data.timestamp);
setMessage("");
setIsSending(false);
};

const handleError = (error: Event) => {
console.log("WebSocket error:", error);
alert("Failed to connect to WebSocket.");
};

const handleClose = () => {
console.log("WebSocket closed");
setConnectionStatus("Disconnected");
wsRef.current = null;
};

const startWebSocket = () => {
if (wsRef.current && wsRef.current.readyState !== WebSocket.CLOSED) {
alert("WebSocket is already open");
return;
}

clearMessages();

const ws = new WebSocket("ws://localhost:8080/ws");
wsRef.current = ws;

ws.onopen = handleOpen;
ws.onmessage = handleMessage;
ws.onerror = handleError;
ws.onclose = handleClose;
};

const stopWebSocket = () => {
if (!wsRef.current) {
alert("WebSocket is not open");
return;
}
wsRef.current.close();
wsRef.current = null;
setConnectionStatus("Disconnected");
};

const sendMessage = async () => {
if (message.trim() === "") {
alert("Message cannot be empty");
return;
}

if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
alert("WebSocket is not open");
return;
}

setIsSending(true);
const jsonMessage = JSON.stringify({ message });
wsRef.current.send(jsonMessage);
setMessage("");
};

return (
<div className="flex flex-col items-center justify-center min-h-screen p-8 pb-20 sm:p-20 font-sans">
<h1 className="text-3xl font-bold">WebSocket Demo App</h1>
<main className="flex flex-col gap-2 items-center w-full max-w-md">
<MessageSection
messages={messages}
message={message}
setMessage={setMessage}
sendMessage={sendMessage}
isDisabled={connectionStatus === "Disconnected" || isSending}
/>
<WebSocketSection
connectionStatus={connectionStatus}
startWebSocket={startWebSocket}
stopWebSocket={stopWebSocket}
/>
</main>
</div>
);
}









Key Functionalities





  1. State Management: Manages connection status, current message, and sending state.


  2. WebSocket Lifecycle: Handles connection setup, events (onopen, onmessage, onerror, onclose), and teardown.


  3. User Interaction: Provides clear feedback and controls for starting/stopping the connection and sending messages.









Conclusion



The HomePage.tsx component demonstrates the integration of WebSocket functionalities with a clean React structure. Its focus on state management and user interaction makes it the backbone of the application's frontend.



In the next article, I will explore the backend implementation using Gin and Go, detailing how the WebSocket server handles connections and messages.









Links to the Series



Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Real-Time Web Application demo with WebSocket - Frontend

Thematisch verwandte Begriffe: RealTime, Application, demo, with · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-96258 | A vulnerability has been found in onSite internet GmbH Auktion NG Auktio…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick