---
title: "How to implement Websocket AP?"  
description: "How to implement Websocket AP?"  
author: "ICSM Computer"  
published: 2025-12-10  
updated: 2025-12-10  
canonical: https://www.mindstick.com/interview/34422/how-to-implement-websocket-ap  
category: "technology"  
tags: ["technology"]  
reading_time: 4 minutes  

---

# How to implement Websocket AP?

## What Is a WebSocket API?

A WebSocket API lets the browser and server stay connected with a **persistent two-way connection**.

- HTTP → Request → Response → Connection CLOSED
- WebSocket → OPEN connection → send/receive anytime

Perfect for:

- Real-time chat
- Notifications
- Live dashboards
- Online games
- Stock/price tickers

## 1. Implement WebSocket in JavaScript (Client)

```javascript
let socket = new WebSocket("ws://localhost:5000/ws/chat");

socket.onopen = function () {
    console.log("Connected to server");
    socket.send("Hello server!");
};

socket.onmessage = function (event) {
    console.log("Message from server:", event.data);
};

socket.onclose = function () {
    console.log("Connection closed");
};

socket.onerror = function (err) {
    console.error("WebSocket error", err);
};

// Send message
function sendMessage(msg) {
    if (socket.readyState === WebSocket.OPEN) {
        socket.send(msg);
    }
}
```

## 2. ASP.NET Core WebSocket Server (Recommended)

(MVC 5 does **NOT** support WebSockets directly.)

### Startup.cs

```plaintext
public void Configure(IApplicationBuilder app)
{
    app.UseWebSockets();

    app.Use(async (context, next) =>
    {
        if (context.Request.Path == "/ws/chat")
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                var socket = await context.WebSockets.AcceptWebSocketAsync();
                await Echo(socket);
            }
            else
            {
                context.Response.StatusCode = 400;
            }
        }
        else
        {
            await next();
        }
    });
}

private async Task Echo(WebSocket socket)
{
    var buffer = new byte[1024 * 4];
    var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

    while (!result.CloseStatus.HasValue)
    {
        var msg = Encoding.UTF8.GetString(buffer, 0, result.Count);

        // Send message back
        await socket.SendAsync(
            Encoding.UTF8.GetBytes("Server: " + msg),
            WebSocketMessageType.Text,
            true,
            CancellationToken.None
        );

        result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
    }

    await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
```

This is a **minimal production-ready WebSocket API**.

## Which One Should YOU Use?

| Technology | Use When |
| --- | --- |
| **ASP.NET Core WebSockets** | You are using .NET Core or .NET 6+ |
| **SignalR (MVC 5)** | You are using .NET Framework MVC 5 |
| **Pure WebSocket** | You need full control, low-level protocol |

## Answers

### Answer by ICSM Computer

## What Is a WebSocket API?

A WebSocket API lets the browser and server stay connected with a **persistent two-way connection**.

- HTTP → Request → Response → Connection CLOSED
- WebSocket → OPEN connection → send/receive anytime

Perfect for:

- Real-time chat
- Notifications
- Live dashboards
- Online games
- Stock/price tickers

## 1. Implement WebSocket in JavaScript (Client)

```javascript
let socket = new WebSocket("ws://localhost:5000/ws/chat");

socket.onopen = function () {
    console.log("Connected to server");
    socket.send("Hello server!");
};

socket.onmessage = function (event) {
    console.log("Message from server:", event.data);
};

socket.onclose = function () {
    console.log("Connection closed");
};

socket.onerror = function (err) {
    console.error("WebSocket error", err);
};

// Send message
function sendMessage(msg) {
    if (socket.readyState === WebSocket.OPEN) {
        socket.send(msg);
    }
}
```

## 2. ASP.NET Core WebSocket Server (Recommended)

(MVC 5 does **NOT** support WebSockets directly.)

### Startup.cs

```plaintext
public void Configure(IApplicationBuilder app)
{
    app.UseWebSockets();

    app.Use(async (context, next) =>
    {
        if (context.Request.Path == "/ws/chat")
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                var socket = await context.WebSockets.AcceptWebSocketAsync();
                await Echo(socket);
            }
            else
            {
                context.Response.StatusCode = 400;
            }
        }
        else
        {
            await next();
        }
    });
}

private async Task Echo(WebSocket socket)
{
    var buffer = new byte[1024 * 4];
    var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

    while (!result.CloseStatus.HasValue)
    {
        var msg = Encoding.UTF8.GetString(buffer, 0, result.Count);

        // Send message back
        await socket.SendAsync(
            Encoding.UTF8.GetBytes("Server: " + msg),
            WebSocketMessageType.Text,
            true,
            CancellationToken.None
        );

        result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
    }

    await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
```

This is a **minimal production-ready WebSocket API**.

## Which One Should YOU Use?

| Technology | Use When |
| --- | --- |
| **ASP.NET Core WebSockets** | You are using .NET Core or .NET 6+ |
| **SignalR (MVC 5)** | You are using .NET Framework MVC 5 |
| **Pure WebSocket** | You need full control, low-level protocol |


---

Original Source: https://www.mindstick.com/interview/34422/how-to-implement-websocket-ap

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
