WebSockets

Azu provides powerful WebSocket support for building real-time applications. With type-safe channels, automatic connection management, and efficient message handling, you can create interactive, responsive user experiences.

What are WebSockets?

WebSockets in Azu provide:

  • Real-time Communication: Bidirectional communication between client and server

  • Type Safety: Type-safe message handling and broadcasting

  • Connection Management: Automatic connection and disconnection handling

  • Event Broadcasting: Notify all connected clients of changes

  • Message Validation: Validate incoming WebSocket messages

Basic WebSocket Channel

class ChatChannel < Azu::Channel
  CONNECTIONS = Set(HTTP::WebSocket).new

  ws "/chat"

  def on_connect
    CONNECTIONS << socket.not_nil!
    send_to_client({
      type: "connected",
      message: "Connected to chat",
      timestamp: Time.utc.to_rfc3339
    })

    Log.info { "User connected. Total connections: #{CONNECTIONS.size}" }
  end

  def on_message(message : String)
    begin
      data = JSON.parse(message)
      handle_message(data)
    rescue JSON::ParseException
      send_error("Invalid JSON format")
    end
  end

  def on_close(code, message)
    CONNECTIONS.delete(socket)
    Log.info { "User disconnected. Total connections: #{CONNECTIONS.size}" }
  end

  private def handle_message(data : JSON::Any)
    case data["type"]?.try(&.as_s)
    when "ping"
      send_to_client({type: "pong", timestamp: Time.utc.to_rfc3339})
    when "message"
      broadcast_message(data["content"].as_s, data["user"].as_s)
    when "typing"
      broadcast_typing(data["user"].as_s, data["is_typing"].as_bool)
    else
      send_error("Unknown message type")
    end
  end

  private def broadcast_message(content : String, user : String)
    message = {
      type: "message",
      content: content,
      user: user,
      timestamp: Time.utc.to_rfc3339
    }

    broadcast_to_all(message)
  end

  private def broadcast_typing(user : String, is_typing : Bool)
    message = {
      type: "typing",
      user: user,
      is_typing: is_typing,
      timestamp: Time.utc.to_rfc3339
    }

    broadcast_to_all(message)
  end

  private def send_to_client(data)
    socket.not_nil!.send(data.to_json)
  end

  private def send_error(message : String)
    send_to_client({type: "error", message: message})
  end

  private def broadcast_to_all(message)
    CONNECTIONS.each do |socket|
      spawn socket.send(message.to_json)
    end
  end
end

Channel Registration

Register WebSocket channels in your application:

Message Types

Handle different types of WebSocket messages:

Text Messages

JSON Messages

Binary Messages

Connection Management

Connection Lifecycle

Connection Validation

Broadcasting

Broadcast to All Connections

Room-based Broadcasting

Real-time Features

Live Notifications

Live Updates

Error Handling

WebSocket Error Handling

Connection Error Handling

Testing WebSockets

Test your WebSocket channels:

Performance Considerations

Connection Pooling

Message Batching

Security Considerations

Authentication

Rate Limiting

Best Practices

1. Handle Connection Lifecycle

2. Validate Messages

3. Use Type Safety

Next Steps

Now that you understand WebSockets:

  1. Components - Build interactive UI components

  2. Templates - Create real-time templates

  3. Caching - Implement WebSocket caching

  4. Testing - Test your WebSocket channels

  5. Performance - Optimize WebSocket performance


WebSockets in Azu provide a powerful foundation for building real-time applications. With type safety, connection management, and efficient broadcasting, they enable interactive, responsive user experiences.

Last updated

Was this helpful?