Create WebSocket Channel

This guide shows you how to create WebSocket channels for real-time communication.

Basic Channel

Create a channel by extending Azu::Channel:

class ChatChannel < Azu::Channel
  PATH = "/chat"

  def on_connect
    # Called when client connects
    send({type: "connected", message: "Welcome!"}.to_json)
  end

  def on_message(message : String)
    # Called when client sends a message
    data = JSON.parse(message)
    # Process message...
  end

  def on_close(code, reason)
    # Called when connection closes
  end
end

Register the Channel

Add your channel to the application:

Client Connection

Connect from JavaScript:

Handling Different Message Types

Connection State

Track connection state:

Authentication

Authenticate WebSocket connections:

Room-based Channels

Create channels with rooms:

Error Handling

Handle errors gracefully:

See Also

Last updated

Was this helpful?