net-core
  1. net-core-real-time-communication

Real-time Communication - (ASP.NET Core WebSockets & SignalR)

Real-time communication enables instant messaging, chat rooms, and live streaming features. With the latest web technologies, real-time communication is easier than ever with WebSockets and SignalR in ASP.NET Core.

WebSockets

WebSockets are a new communication protocol in HTML5, which provides a persistent connection between the client and the server. Using WebSockets, you can send and receive data in real-time without the need for constant HTTP requests.

Syntax

Here is the syntax for creating a WebSocket endpoint in ASP.NET Core:

app.UseWebSockets();

app.Map("/chat", async (context, next) =>
{
    if (context.WebSockets.IsWebSocketRequest)
    {
        using var webSocket = await context.WebSockets.AcceptWebSocketAsync();

        while (webSocket.State == WebSocketState.Open)
        {
            // Receive message
            var buffer = new byte[2048];
            var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

            // Echo message back to the client
            if (result.MessageType == WebSocketMessageType.Text)
            {
                var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
                var bytes = Encoding.UTF8.GetBytes($"Echo: {message}");
                await webSocket.SendAsync(new ArraySegment<byte>(bytes, 0, bytes.Length), result.EndOfMessage, CancellationToken.None);
            }
        }

        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "WebSocket closed", CancellationToken.None);
    }
    else
    {
        context.Response.StatusCode = 400;
    }
});

Example

Here is an example of a WebSockets chat application that sends and receives messages in real-time.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>WebSocket Chat</title>
</head>
<body>
    <input type="text" placeholder="Enter a message" id="message-input" />
    <button id="send-button">Send</button>
    <hr />
    <ul id="messages"></ul>

    <script>
        const socket = new WebSocket('ws://localhost:5000/chat');

        // Send message on click
        document.getElementById('send-button').addEventListener('click', () => {
            const message = document.getElementById('message-input').value;
            socket.send(message);
        });

        // Handle incoming messages
        socket.addEventListener('message', event => {
            const message = document.createElement('li');
            message.textContent = event.data;
            document.getElementById('messages').appendChild(message);
        });
    </script>
</body>
</html>

Output

When you run the example and open the HTML page in your browser, you should be able to enter messages and receive the same message back immediately.

SignalR

SignalR is a library that simplifies real-time communication in ASP.NET Core. It provides high-level APIs for building real-time web applications.

Syntax

Here is the syntax for creating a SignalR hub in ASP.NET Core:

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

Example

Here is an example of a SignalR chat application that receives messages in real-time.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>SignalR Chat</title>
</head>
<body>
    <input type="text" placeholder="Enter a message" id="message-input" />
    <button id="send-button">Send</button>
    <hr />
    <ul id="messages"></ul>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="/chatHub"></script>
    <script>
        const connection = new signalR.HubConnectionBuilder().withUrl('/chatHub').build();

        // Start the connection
        connection.start().catch(error => console.error(error.toString()));

        // Send message on click
        document.getElementById('send-button').addEventListener('click', () => {
            const user = 'User';
            const message = document.getElementById('message-input').value;
            connection.invoke('SendMessage', user, message).catch(error => console.error(error.toString()));
        });

        // Handle incoming messages
        connection.on('ReceiveMessage', (user, message) => {
            const messageElement = document.createElement('li');
            messageElement.textContent = `${user}: ${message}`;
            document.getElementById('messages').appendChild(messageElement);
        });
    </script>
</body>
</html>

Explanation

WebSockets and SignalR in ASP.NET Core provide an efficient and scalable way to enable real-time communication in your web applications. WebSockets provides low-level network communication, while SignalR is a high-level library that simplifies the process of building real-time web applications.

Use

Real-time communication is essential in modern web applications. With WebSockets and SignalR in ASP.NET Core, you can build real-time web applications like chat rooms, instant messaging services, online gaming, and more.

Important Points

  • WebSockets provide persistent connections between the client and the server.
  • SignalR is a library that simplifies real-time communication in ASP.NET Core.
  • Real-time communication is essential in modern web applications.

Summary

In this page, we discussed how to enable real-time communication using WebSockets and SignalR in ASP.NET Core. We covered the syntax, example, output, explanation, use, important points, and summary of real-time communication in ASP.NET Core. With WebSockets and SignalR, you can build fast and scalable real-time web applications.

Published on: