Channel

Channels handle WebSocket connections for real-time communication.

Extending Channel

class MyChannel < Azu::Channel
  PATH = "/ws/path"

  def on_connect
    # Handle connection
  end

  def on_message(message : String)
    # Handle message
  end

  def on_close(code, reason)
    # Handle disconnection
  end
end

Class Constants

PATH

Define the WebSocket endpoint path.

Lifecycle Methods

on_connect

Called when a client connects.

on_message

Called when a message is received.

Parameters:

  • message : String - Raw message from client

on_close

Called when connection closes.

Parameters:

  • code : Int32? - Close code

  • reason : String? - Close reason

on_error

Called on WebSocket error.

Instance Methods

socket

Access the WebSocket instance.

Returns: HTTP::WebSocket

send

Send a message to the connected client.

Parameters:

  • message : String - Message to send

close

Close the WebSocket connection.

Parameters:

  • code : Int32? - Close code

  • reason : String? - Close reason

context

Access the HTTP context.

Returns: HTTP::Server::Context

params

Access route parameters.

Returns: Hash(String, String)

headers

Access request headers.

Returns: HTTP::Headers

Broadcasting

Class-level broadcasting

Broadcast to others

Room Management

Authentication

Message Handling Pattern

Complete Example

See Also

Last updated

Was this helpful?