Introduction - potatoscript/websocket GitHub Wiki

๐Ÿ“ก Introduction to WebSockets

๐Ÿš€ What is WebSocket?

WebSocket is a special communication system that lets computers talk to each other instantly without waiting!

๐Ÿ’ก Imagine:

  • HTTP (old way) ๐Ÿ“จ โ†’ Like sending a letter to a friend and waiting for a reply.
  • WebSocket (new way) ๐Ÿ”„ โ†’ Like talking on the phone โ€“ instant messages!

๐Ÿ”ฅ Why Use WebSockets?

โœ… Fast โ€“ Messages are sent in real-time (no delays!)
โœ… Lightweight โ€“ Uses fewer resources than HTTP
โœ… Two-way Communication โ€“ The server and the client can send messages anytime!
โœ… Great for Real-time Apps โ€“ Chat apps, multiplayer games, stock price updates


๐Ÿ— Step 1: Setting Up a WebSocket Server

๐Ÿ“Œ Let's create a simple WebSocket server using Node.js!

๐Ÿ“Œ 1๏ธโƒฃ Install Node.js

๐Ÿ”น First, make sure you have Node.js installed.
๐Ÿ”น Download it from here and install it.

To check if it's installed, open your terminal (Command Prompt or Terminal) and type:

node -v

If it shows a version number, you're ready! โœ…


๐Ÿ“Œ 2๏ธโƒฃ Create a New Project

Now, letโ€™s create a folder for our WebSocket project:

mkdir websocket-demo
cd websocket-demo

Inside this folder, initialize a Node.js project:

npm init -y

This will create a file called package.json (it keeps track of our project settings).


๐Ÿ“Œ 3๏ธโƒฃ Install WebSocket Library

We need a special tool to create WebSockets in Node.js. Letโ€™s install it:

npm install ws

๐Ÿ”Œ Step 2: Create the WebSocket Server

๐Ÿ“Œ Now, let's create our WebSocket server!

1๏ธโƒฃ Inside your websocket-demo folder, create a new file called server.js.
2๏ธโƒฃ Open it and add this code:

// 1๏ธโƒฃ Import the WebSocket library
const WebSocket = require('ws');

// 2๏ธโƒฃ Create a WebSocket Server on port 8080
const wss = new WebSocket.Server({ port: 8080 });

console.log("๐Ÿ“ก WebSocket Server is running on ws://localhost:8080");

// 3๏ธโƒฃ Handle new connections
wss.on('connection', (ws) => {
    console.log("โœ… A new client connected!");

    // 4๏ธโƒฃ Send a welcome message to the client
    ws.send("๐ŸŽ‰ Welcome to the WebSocket Server!");

    // 5๏ธโƒฃ Listen for messages from the client
    ws.on('message', (message) => {
        console.log(`๐Ÿ“ฉ Received: ${message}`);
        
        // 6๏ธโƒฃ Send back a reply
        ws.send(`๐Ÿ“ Server says: You said "${message}"`);
    });

    // 7๏ธโƒฃ Handle client disconnection
    ws.on('close', () => {
        console.log("โŒ A client disconnected");
    });
});

๐Ÿ” Explanation:
โœ” We create a WebSocket server on port 8080.
โœ” When a client connects, we send a welcome message.
โœ” When the client sends a message, the server replies.
โœ” If the client disconnects, we log it.

โœ… Now, run the WebSocket server in the terminal:

node server.js

๐ŸŽ‰ Your WebSocket server is now running!


๐Ÿ’ป Step 3: Create a WebSocket Client (in the Browser)

๐Ÿ“Œ Letโ€™s connect to our WebSocket server using a web page!

1๏ธโƒฃ Create a new file called index.html inside your websocket-demo folder.
2๏ธโƒฃ Open it and add this code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Demo</title>
</head>
<body>
    <h1>๐Ÿ“ก WebSocket Client</h1>
    <p>Status: <span id="status">๐Ÿ”ด Disconnected</span></p>
    <input type="text" id="messageInput" placeholder="Type a message..." />
    <button onclick="sendMessage()">๐Ÿš€ Send</button>
    <ul id="messages"></ul>

    <script>
        // 1๏ธโƒฃ Connect to WebSocket Server
        const socket = new WebSocket("ws://localhost:8080");

        // 2๏ธโƒฃ Update status when connected
        socket.onopen = () => {
            document.getElementById("status").textContent = "๐ŸŸข Connected";
        };

        // 3๏ธโƒฃ Receive messages from the server
        socket.onmessage = (event) => {
            const messageList = document.getElementById("messages");
            const newMessage = document.createElement("li");
            newMessage.textContent = `๐Ÿ“ฉ ${event.data}`;
            messageList.appendChild(newMessage);
        };

        // 4๏ธโƒฃ Send a message to the server
        function sendMessage() {
            const input = document.getElementById("messageInput");
            const message = input.value;
            socket.send(message);
            input.value = "";
        }

        // 5๏ธโƒฃ Handle disconnection
        socket.onclose = () => {
            document.getElementById("status").textContent = "๐Ÿ”ด Disconnected";
        };
    </script>
</body>
</html>

โœ… Now, open index.html in a browser and test your WebSocket!

  • Type a message and click "Send" โ†’ The server will reply instantly!
  • If the server is stopped, the status will turn red ๐Ÿ”ด.

๐ŸŽฏ Step 4: Test Everything!

1๏ธโƒฃ Start the WebSocket server:

node server.js

2๏ธโƒฃ Open index.html in a browser.
3๏ธโƒฃ Send messages! ๐ŸŽ‰


๐ŸŽฎ Bonus: What Can You Build with WebSockets?

โœ” Real-time Chat Apps ๐Ÿ’ฌ
โœ” Multiplayer Games ๐ŸŽฎ
โœ” Live Stock Market Updates ๐Ÿ“ˆ
โœ” IoT Device Communication ๐Ÿค–


๐ŸŽฏ Final Thoughts

Congratulations! ๐ŸŽ‰ You have learned:
โœ… What WebSocket is ๐Ÿ“ก
โœ… How to create a WebSocket server โšก
โœ… How to connect from a browser ๐ŸŒ
โœ… How to send & receive messages โœ‰

โš ๏ธ **GitHub.com Fallback** โš ๏ธ