Isaac.

Implement WebSockets for Real-time Communication

Table of Contents

  • Why WebSockets?
  • ASP.NET Example
  • Spring Boot Example
  • Express Example
  • Next.js Example
  • Flask Example
  • Laravel Example
  • Conclusion

Why WebSockets?

WebSockets provide a full-duplex, low-latency communication channel between clients and servers, allowing real-time features like chat, notifications, live updates, and online games.

Unlike HTTP, which is request/response based, WebSockets keep a persistent connection so the server can push updates instantly.

ASP.NET WebSocket Example

This ASP.NET Core example shows how to implement a WebSocket server.

using System.Net.WebSockets;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Threading.Tasks;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseWebSockets();

app.Map("/ws", async context =>
{{
    if (context.WebSockets.IsWebSocketRequest)
    {{
        var webSocket = await context.WebSockets.AcceptWebSocketAsync();
        var buffer = new byte[1024 * 4];
        var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        while (!result.CloseStatus.HasValue)
        {{
            var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
            var response = Encoding.UTF8.GetBytes($"Server received: {message}");
            await webSocket.SendAsync(new ArraySegment<byte>(response), 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);
    }}
}});

app.Run();

This code sets up a WebSocket endpoint at /ws. It receives messages and echoes them back to the client.

Spring Boot Example

// Spring Boot WebSocket Example
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {{
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {{
        registry.addHandler(new MyHandler(), "/ws").setAllowedOrigins("*");
    }}
}}

public class MyHandler extends TextWebSocketHandler {{
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {{
        session.sendMessage(new TextMessage("Server received: " + message.getPayload()));
    }}
}}

Express Example

const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

wss.on('connection', ws => {{
    ws.on('message', message => {{
        ws.send('Server received: ' + message);
    }});
}});

server.listen(3000, () => console.log('Server running on port 3000'));

Next.js Example

// next.config.js (custom server)
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {{
    const server = express();
    const httpServer = http.createServer(server);
    const wss = new WebSocket.Server({ server: httpServer });

    wss.on('connection', ws => {{
        ws.on('message', message => {{
            ws.send('Server received: ' + message);
        }});
    }});

    server.all('*', (req, res) => handle(req, res));
    httpServer.listen(3000, () => console.log('Next.js server running on port 3000'));
}});

Flask Example

from flask import Flask
from flask_socketio import SocketIO, send

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on('message')
def handle_message(msg):
    send('Server received: ' + msg)

if __name__ == '__main__':
    socketio.run(app)

Laravel Example

// Laravel WebSocket Example (using beyondcode/laravel-websockets)
// routes/web.php
use BeyondCodeLaravelWebSocketsWebSocketsWebSocketHandler;

WebSocketHandler::on('message', function ($connection, $message) {
    $connection->send('Server received: ' . $message);
});

Conclusion

WebSockets enable real-time, low-latency communication for modern web apps. ASP.NET provides a robust way to implement WebSockets, and other frameworks like Spring Boot, Express, Next.js, Flask, and Laravel also offer reliable options.

Ignoring WebSockets in applications that require instant updates can lead to poor user experience, higher latency, and unnecessary polling overhead.