Connection - potatoscript/websocket GitHub Wiki

🌐 Basic Connection

What is a WebSocket Connection? πŸ€”

A WebSocket connection is like a magic telephone ☎️ that lets the client (browser) and server talk to each other instantly! Unlike normal web pages that keep asking for new messages, WebSockets allow us to send and receive messages instantly in real time.


βš™οΈ Step 1: Create a WebSocket Server

πŸ’‘ Why do we need a server?
The server is like a radio station πŸ“‘β€”it sends and receives messages from clients (browsers).

πŸ“Œ Create a New JavaScript File

1️⃣ Open your project folder websocket-demo.
2️⃣ Create a new file called server.js.
3️⃣ Open the file in VS Code or any code editor.


πŸ“Œ Write the WebSocket Server Code

Inside server.js, add the following code:

// πŸ› οΈ Import the WebSocket library
const WebSocket = require("ws");

// πŸ“‘ Create a WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });

console.log("βœ… WebSocket server is running on ws://localhost:8080");

// πŸ“ž Listen for client connections
wss.on("connection", (ws) => {
    console.log("πŸ”— A client has connected!");

    // πŸ“© Listen for messages from the client
    ws.on("message", (message) => {
        console.log("πŸ“¨ Received:", message.toString());
        
        // πŸ”„ Send a reply back to the client
        ws.send("πŸ”” Server says: Message received!");
    });

    // ❌ Handle client disconnections
    ws.on("close", () => {
        console.log("πŸšͺ A client has disconnected.");
    });
});

πŸ“ Explanation of the Code

βœ… Import the WebSocket library to use WebSockets.
πŸ“‘ Create a WebSocket server that listens on port 8080.
πŸ“ž Detect when a client connects and send/receive messages.
πŸ“¨ Print received messages and send a response.
πŸšͺ Handle disconnections when a client leaves.


πŸš€ Step 2: Run the WebSocket Server

πŸ’‘ Now, let’s start our server!

1️⃣ Open your terminal or command prompt.
2️⃣ Make sure you're inside the websocket-demo folder.
3️⃣ Run this command:

node server.js

4️⃣ You should see:

βœ… WebSocket server is running on ws://localhost:8080

πŸŽ‰ Congratulations! Your WebSocket server is now running! πŸŽ‰


πŸ–₯️ Step 3: Create a WebSocket Client (HTML + JavaScript)

πŸ’‘ Now we need a "listener" (client) to connect to our server!

πŸ“Œ Create a New HTML File

1️⃣ Create a new file called client.html inside your websocket-demo folder.
2️⃣ Open the file in VS Code or any text editor.


πŸ“Œ Write the WebSocket Client Code

Inside client.html, 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 Client 🌐</title>
</head>
<body>
    <h2>πŸ“‘ WebSocket Client</h2>
    <button onclick="sendMessage()">πŸ“© Send Message</button>
    <p id="status">πŸ”΄ Disconnected</p>
    <p id="messages"></p>

    <script>
        // πŸ”Œ Create a WebSocket connection to the server
        const socket = new WebSocket("ws://localhost:8080");

        // πŸ”„ Connection opened
        socket.onopen = function () {
            document.getElementById("status").textContent = "🟒 Connected to Server!";
            console.log("βœ… Connected to WebSocket server");
        };

        // πŸ“© Handle incoming messages
        socket.onmessage = function (event) {
            console.log("πŸ“¨ Server:", event.data);
            document.getElementById("messages").innerHTML += "<p>πŸ“¨ " + event.data + "</p>";
        };

        // πŸšͺ Handle connection close
        socket.onclose = function () {
            document.getElementById("status").textContent = "πŸ”΄ Disconnected";
            console.log("❌ Disconnected from WebSocket server");
        };

        // πŸ“€ Send a message to the server
        function sendMessage() {
            socket.send("Hello Server! 🌍");
            console.log("πŸ“© Sent: Hello Server! 🌍");
        }
    </script>
</body>
</html>

πŸ“ Explanation of the Code

🟒 Creates a WebSocket connection to the server.
πŸ“© Sends a message when the button is clicked.
πŸ“¨ Receives messages from the server and displays them.
πŸ”΄ Handles disconnections when the server stops.


πŸš€ Step 4: Test the WebSocket Connection

1️⃣ Start the WebSocket server:

node server.js

βœ… You should see:

βœ… WebSocket server is running on ws://localhost:8080

2️⃣ Open the client (HTML page):

  • Open client.html in a web browser (Chrome, Edge, Firefox).
  • You should see "WebSocket Client" and a πŸ“© Send Message button.

3️⃣ Click the "πŸ“© Send Message" button:

  • The server will print:
    πŸ“¨ Received: Hello Server! 🌍
    
  • The client will display:
    πŸ”” Server says: Message received!
    

  • Connect to your webSocket

    • const ws = new WebSocket('ws://127.0.0.1:9876')
  • Send message ws.send("some message here")

  • Access connection from the front end to the back end

    • install nodemon npm i -g nodemon
    • next run nodemon index.js
    • after install the nodemon and run it you can receive the message with
     const WebSocket = require('ws')
    
     const wss = new WebSocket.Server({
        port: 9876
     })
    
     wss.on('connection', function(ws){
        ws.send("Hello from the server")
     })
  • to get the message data of client from the server

ws.on('message',function(data){
   console.log(data)
})
  • to get the message data of server from the client
ws.onmessage=function(data, isBinary){
    const message = isBinary ? data : data.toString();
    console.log(message)
}
  • resend back the message of client from the server
ws.on('message',function message(data, isBinary){
   const message = isBinary ? data : data.toString();
   ws.send(message)
})
  • To make a connection from client side
const url = 'ws://localhost:9876/websocket'
const server = new WebSocket(url)

server.onopen = function(){
    server.send("Hi")
    server.send("this is lim")
}
  • add multiple client in the server
wss.on('connection', function(ws){
    //ws.send("Hello from the server")
    ws.on('message',function message(data, isBinary){
       const message = isBinary ? data : data.toString();
       //ws.send(message)
       wss.clients.forEach(function each(client){
           if(client.readyState === WebSocket.OPEN){
                client.send(message)
           }
       })
    })
})
  • webSocket readyState
    • image
⚠️ **GitHub.com Fallback** ⚠️