Skip to content

Commit e822545

Browse files
committed
feat: add websockets documentation
1 parent 53720e6 commit e822545

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

advanced/websockets.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// 📌 JavaScript Advanced - WebSockets
2+
3+
// Welcome to the WebSockets section of the JavaScript Advanced tutorial!
4+
// Here, you'll learn how to implement real-time communication using WebSockets.
5+
6+
// Creating a WebSocket Connection
7+
const socket = new WebSocket("wss://example.com/socket");
8+
9+
// Event Listeners for WebSocket
10+
// Connection opened
11+
socket.addEventListener("open", (event) => {
12+
console.log("Connected to WebSocket server");
13+
socket.send("Hello Server!"); // Sending data
14+
});
15+
16+
// Receiving messages
17+
socket.addEventListener("message", (event) => {
18+
console.log("Message from server:", event.data);
19+
});
20+
21+
// Handling errors
22+
socket.addEventListener("error", (event) => {
23+
console.error("WebSocket error:", event);
24+
});
25+
26+
// Connection closed
27+
socket.addEventListener("close", (event) => {
28+
console.log("WebSocket connection closed:", event);
29+
});
30+
31+
// Sending JSON Data
32+
const jsonData = JSON.stringify({ user: "JohnDoe", message: "Hello!" });
33+
socket.send(jsonData);
34+
35+
// 💡 WebSockets are great for chat apps, live notifications, and real-time collaboration!

0 commit comments

Comments
 (0)