@@ -22,7 +22,7 @@ const clients = [];
2222app . post ( "/message" , ( req , res ) => {
2323 const { message, name } = req . body
2424
25- if ( ! message . trim ( ) || ! name . trim ( ) ) {
25+ if ( ! message . trim ( ) || ! name . trim ( ) ) {
2626 return res . status ( 400 ) . json ( {
2727 error : "Name and message are required"
2828 } )
@@ -53,20 +53,15 @@ app.post("/message", (req, res) => {
5353
5454//webSocket
5555
56- // we need to create a server manually
5756const http = require ( "http" ) ;
5857const server = http . createServer ( app ) ;
5958
6059server . listen ( 3000 , ( ) => {
6160 console . log ( "server is running in this port" )
6261} )
63- //Then create the WebSocket server:
62+
6463const wss = new WebSocket . Server ( { server } ) ;
65- /*✅ What this means
66- wss = your WebSocket server
67- It is connected to your HTTP server ✅
68- It’s now ready to accept connections ✅
69- */
64+
7065wss . on ( "connection" , ( ws ) => {
7166 console . log ( "New client connected" ) ;
7267 clients . push ( ws ) ;
@@ -77,50 +72,4 @@ wss.on("connection", (ws) => {
7772 clients . splice ( index , 1 ) ;
7873 } ) ;
7974
80- } ) ;
81- //Each ws = one connected user
82- //You detect when a user connects ✅
83- //But you don’t remember them ❌
84-
85-
86-
87- //✅ STEP 3 — Store connected clients
88- // const clients = [];
89-
90- //✅ STEP 4 — Handle disconnections (VERY important)
91- /* ws.on("close", () => {
92- console.log("Client disconnected");
93-
94- // remove this client from the array
95- const index = clients.indexOf(ws);
96- clients.splice(index, 1);
97- });
98- ✅ What this means (simple)
99-
100- ws.on("close") → runs when user leaves
101- indexOf(ws) → find that user
102- splice(...) → remove them
103-
104- ✅ STEP 5 — Broadcast message to all clients
105- Right now:
106-
107- You store messages ✅
108- You track connected users ✅
109- But you don’t send messages to them yet ❌
110- ✅ Goal of this step
111- 👉 When a new message is posted:
112-
113- Send it to every connected client instantly
114- clients.forEach((client) => {
115- client.send(JSON.stringify({
116- name,
117- message
118- }));
119- });
120- ``
121- JSON.stringify → convert object → text (required)
122- WebSockets only send strings, not objects
123-
124-
125- */
126-
75+ } ) ;
0 commit comments