CodeGym /Courses /Frontend SELF EN /Introduction to WebSocket

Introduction to WebSocket

Frontend SELF EN
Level 46 , Lesson 1
Available

6.1 Basic WebSocket Concepts

WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It allows two-way data transmission between the client and server, making it perfect for applications requiring constant real-time data exchange like chat apps, online games, and notification systems.

Advantages of WebSocket

  1. Two-way communication: WebSocket provides two-way data transmission, allowing both server and client to send messages to each other anytime.
  2. Lower latency: Compared with traditional HTTP requests, WebSocket reduces latency thanks to its persistent connection.
  3. Less load on the server: WebSocket reduces the number of HTTP requests, thus reducing server load.

Main WebSocket Components

  1. WebSocket Server: The server side that accepts and processes WebSocket connections.
  2. WebSocket Client: The client side that establishes a connection to the WebSocket server and exchanges data.

6.2 Working with WebSocket in JavaScript

You work with WebSocket in JavaScript using the WebSocket object, which provides methods to establish connections, send and receive messages, and handle events.

Creating a WebSocket connection:

JavaScript
    
      const socket = new WebSocket('ws://server.example.com/chat');
    
  

WebSocket Events:

  1. open: triggers when the connection is established.
  2. message: triggers when a message is received from the server.
  3. error: triggers upon an error.
  4. close: triggers when the connection is closed.

Example of using WebSocket:

JavaScript
    
      const socket = new WebSocket('ws://server.example.com/chat');

      socket.addEventListener('open', (event) => {
        console.log('Connected to the WebSocket server');
        socket.send('Hello Server!');
      });

      socket.addEventListener('message', (event) => {
        console.log('Message from server:', event.data);
      });

      socket.addEventListener('error', (event) => {
        console.error('WebSocket error:', event);
      });

      socket.addEventListener('close', (event) => {
        console.log('Disconnected from WebSocket server');
      });
    
  

6.3 WebSocket Server Example in Node.js

To create a WebSocket server, you can use the ws library in Node.js.

Installing the library:

Terminal
    
      npm install ws
    
  

WebSocket Server Example:

JavaScript
    
      const WebSocket = require('ws');
      const wss = new WebSocket.Server({ port: 8080 });

      wss.on('connection', (ws) => {
        console.log('New client connected');

        ws.on('message', (message) => {
          console.log('Received:', message);
          ws.send(`Server says: ${message}`);
        });

        ws.on('close', () => {
          console.log('Client disconnected');
        });
      });

      console.log('WebSocket server is running on ws://localhost:8080');
    
  

6.4 Main WebSocket Events and Methods

Client-side events:

  • onopen: triggers when the WebSocket connection is established
  • onmessage: triggers when a message is received from the server
  • onclose: triggers when the WebSocket connection is closed
  • onerror: triggers upon a WebSocket error

Client-side methods

  • send(data): sends data to the server
  • close(code, reason): closes the WebSocket connection with the specified code and reason

Server-side events

  • connection: triggers when a client connects to the server
  • message: triggers when the server receives a message from the client
  • close: triggers when the WebSocket connection is closed
  • error: triggers upon a WebSocket error

Server-side methods

  • send(data): sends data to the client
  • close(code, reason): closes the WebSocket connection with the specified code and reason

6.5 WebSocket Usage Examples

Example: Real-time Chat

Client-side:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>WebSocket Chat</title>
        </head>
        <body>
          <input type="text" id="message" placeholder="Enter your message" />
          <button onclick="sendMessage()">Send</button>
          <div id="chat"></div>

          <script>
            const socket = new WebSocket('ws://localhost:8080');
            const chat = document.getElementById('chat');

            socket.onopen = function() {
              console.log('WebSocket is open now.');
            };

            socket.onmessage = function(event) {
              const message = document.createElement('p');
              message.textContent = event.data;
              chat.appendChild(message);
            };

            socket.onclose = function() {
              console.log('WebSocket is closed now.');
            };

            socket.onerror = function(event) {
              console.error('WebSocket error observed:', event);
            };

            function sendMessage() {
              const messageInput = document.getElementById('message');
              const message = messageInput.value;
              socket.send(message);
              messageInput.value = '';
            }
          </script>
        </body>
      </html>
    
  

Server-side:

JavaScript
    
      const WebSocket = require('ws');

      const server = new WebSocket.Server({ port: 8080 });

      server.on('connection', (ws) => {
        console.log('New client connected!');

        ws.on('message', (message) => {
          console.log('Received:', message);
          // Broadcast the message to all connected clients
          server.clients.forEach(client => {
            if (client.readyState === WebSocket.OPEN) {
              client.send(message);
            }
          });
        });

        ws.on('close', () => {
          console.log('Client disconnected');
        });

        ws.on('error', (error) => {
          console.error('WebSocket error:', error);
        });
      });

      console.log('WebSocket server is running on ws://localhost:8080');
    
  
1
Task
Frontend SELF EN, level 46, lesson 1
Locked
WebSocket Connection
WebSocket Connection
1
Task
Frontend SELF EN, level 46, lesson 1
Locked
WebSocket Chat
WebSocket Chat
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION