Adding WebSockets

This tutorial teaches you how to add real-time features to your Azu application using WebSocket channels.

What You'll Build

By the end of this tutorial, you'll have:

  • A WebSocket channel for real-time notifications

  • Broadcasting messages to connected clients

  • Client-side WebSocket connection handling

  • Understanding of the channel lifecycle

Prerequisites

Step 1: Understanding WebSocket Channels

WebSocket channels in Azu provide:

  • Persistent connections - Clients stay connected for real-time updates

  • Bidirectional communication - Both server and client can send messages

  • Broadcasting - Send messages to all connected clients

  • Lifecycle events - Handle connect, message, and disconnect events

Step 2: Create a Notification Channel

Create src/channels/notification_channel.cr:

Step 3: Add Broadcasting to Your API

Update src/endpoints/create_user_endpoint.cr to broadcast when users are created:

Similarly update delete and update endpoints to broadcast their events.

Step 4: Update the Main Application

Update src/user_api.cr to include the channel:

Step 5: Create a Client Page

Create public/index.html:

Step 6: Add Static File Handler

Update your application to serve static files:

Step 7: Test Real-time Updates

  1. Start the server:

  2. Open http://localhost:4000/ in your browser

  3. In another terminal, create a user:

  4. Watch the notification appear in your browser in real-time!

Creating a Chat Room

For room-based broadcasting, use a message-based room join pattern:

Key Concepts Learned

Channel Lifecycle

Broadcasting Patterns

Message Protocol

Use a type field to route messages:

Next Steps

You've added real-time features to your API. Continue learning with:


Real-time features unlocked! Your application now supports live updates via WebSockets.

Last updated

Was this helpful?