Integrating WebSockets in Angular and React for Real-Time Apps

Integrate WebSockets in Angular & React | Real-Time App Guide

In modern web applications, real-time updates have become an essential feature for improving user experience. Whether it's live notifications, instant messaging, stock market updates, or collaborative editing, WebSockets play a vital role in achieving real-time communication. This article will explore how to integrate WebSockets in Angular and React applications, focusing on setting up WebSocket APIs in .NET Core, implementing real-time UI updates in both frameworks, and optimizing real-time data streaming.

1. Understanding WebSockets

1.1 What are WebSockets?

WebSockets provide a full-duplex communication channel over a single TCP connection. Unlike traditional HTTP requests, which follow a request-response model, WebSockets enable persistent connections, allowing instant data transmission between the client and server.

1.2 Why Use WebSockets?

  • Low Latency: WebSockets reduce latency compared to polling or long-polling techniques.
  • Efficient Data Exchange: They reduce the overhead of repeated HTTP requests.
  • Bi-Directional Communication: Data can be sent and received in real-time.
  • Scalability: WebSockets allow applications to scale better for real-time features.

2. Setting Up WebSocket APIs in .NET Core

.NET Core provides built-in support for WebSockets, making it easy to integrate real-time communication into backend applications.

2.1 Creating a .NET Core Web API with WebSocket Support

  1. Create a New ASP.NET Core Web API Project

    dotnet new webapi -n WebSocketApp
    cd WebSocketApp
    
  2. Modify the Startup.cs or Program.cs to Enable WebSockets

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseWebSockets();
        app.UseRouting();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/ws", async context =>
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
                    await HandleWebSocket(webSocket);
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            });
        });
    }
    
  3. Handling WebSocket Messages

    private async Task HandleWebSocket(WebSocket webSocket)
    {
        var buffer = new byte[1024 * 4];
        WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
    
        while (!result.CloseStatus.HasValue)
        {
            await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
            result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        }
    
        await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
    }
    

3. Implementing Real-Time UI Updates in Angular

Angular provides a built-in WebSocketSubject via RxJS, making it easy to integrate WebSockets.

3.1 Creating a WebSocket Service

import { Injectable } from '@angular/core';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';

@Injectable({ providedIn: 'root' })
export class WebSocketService {
    private socket$: WebSocketSubject<any>;
    private readonly url = 'ws://localhost:5000/ws';

    constructor() {
        this.socket$ = webSocket(this.url);
    }

    sendMessage(message: any): void {
        this.socket$.next(message);
    }

    getMessages() {
        return this.socket$.asObservable();
    }
}

3.2 Using WebSocket Service in a Component

import { Component, OnInit } from '@angular/core';
import { WebSocketService } from './web-socket.service';

@Component({
  selector: 'app-live-updates',
  template: '<div *ngFor="let msg of messages">{{ msg }}</div>'
})
export class LiveUpdatesComponent implements OnInit {
  messages: string[] = [];

  constructor(private wsService: WebSocketService) {}

  ngOnInit() {
    this.wsService.getMessages().subscribe(msg => this.messages.push(msg));
  }

  sendMessage() {
    this.wsService.sendMessage("Hello from Angular");
  }
}

4. Implementing Real-Time UI Updates in React

React can use the WebSocket API directly or leverage third-party libraries like socket.io-client.

4.1 Creating a WebSocket Hook

import { useEffect, useState } from 'react';

export default function useWebSocket(url) {
    const [messages, setMessages] = useState([]);
    let socket;

    useEffect(() => {
        socket = new WebSocket(url);
        socket.onmessage = (event) => {
            setMessages(prev => [...prev, event.data]);
        };

        return () => {
            socket.close();
        };
    }, [url]);

    const sendMessage = (message) => {
        socket.send(message);
    };

    return { messages, sendMessage };
}

4.2 Using the Hook in a Component

import React from 'react';
import useWebSocket from './useWebSocket';

const LiveUpdates = () => {
    const { messages, sendMessage } = useWebSocket('ws://localhost:5000/ws');

    return (
        <div>
            {messages.map((msg, index) => (
                <div key={index}>{msg}</div>
            ))}
            <button onClick={() => sendMessage("Hello from React")}>Send Message</button>
        </div>
    );
};

export default LiveUpdates;

5. Optimizing Real-Time Data Streaming

  • Throttle/Frequency Control: Limit data updates to prevent UI overload.
  • Compression: Use Gzip or Brotli for large data packets.
  • Connection Management: Auto-reconnect when WebSocket connection drops.
  • Security: Use WSS (WebSocket Secure) instead of WS for encrypted communication.
  • Load Balancing: Implement WebSocket clustering for high-traffic applications.

Conclusion

Integrating WebSockets in Angular and React provides a robust way to achieve real-time updates. With .NET Core as the backend, developers can create scalable and efficient real-time applications. By following best practices like optimizing data transmission and implementing reconnection strategies, you can enhance user experience significantly. Whether you are building chat applications, financial dashboards, or multiplayer games, WebSockets remain a top choice for real-time data exchange.

Sandip Mhaske

I’m a software developer exploring the depths of .NET, AWS, Angular, React, and digital entrepreneurship. Here, I decode complex problems, share insightful solutions, and navigate the evolving landscape of tech and finance.

Post a Comment

Previous Post Next Post