{"title":"Sockets","description":"Connect Amber V2 client sockets to generated WebSocket channels","section":"guides/websockets","version":"v2","path":"guides/websockets/sockets","canonical_url":"https://amberframework.org/docs/v2/guides/websockets/sockets","markdown_url":"https://amberframework.org/docs/v2/guides/websockets/sockets.md","inherited":false,"content_markdown":"# Sockets\n\nA client socket represents one WebSocket connection and maps topic patterns to\nchannel classes. Amber CLI V2 generates channels, while the socket boundary is\ncurrently hand-authored.\n\n**Run from: the application root.**\n\n```bash\namber generate channel ChatRoom --topics=chat_room\n```\n\n**File: `src/sockets/chat_socket.cr` — create this socket struct, then ensure\nthe application requires `src/sockets/**` before routes compile.**\n\n```crystal\nstruct ChatSocket < Amber::WebSockets::ClientSocket\n  channel \"chat_room:*\", ChatRoomChannel\n\n  def on_connect : Bool\n    # `session`, `cookies`, and validated `params` are available here.\n    !!session[:current_user_id]?\n  end\nend\n```\n\n**File: `config/routes.cr` — add the handshake route inside the existing\n`routes :web` block.**\n\n```crystal\nAmber::Server.configure do\n  routes :web do\n    websocket \"/chat\", ChatSocket\n  end\nend\n```\n\nReturn `false` from `on_connect` to reject the connection. Override\n`on_disconnect`, `on_reconnect`, or `on_error` when the application needs\nconnection lifecycle behavior.\n\n**File: the controller or service that owns the event, under `src/controllers/`\nor `src/services/` — broadcast after the application operation succeeds.**\n\n```crystal\nChatSocket.broadcast(\n  \"message\",\n  \"chat_room:123\",\n  \"message_new\",\n  {\"message\" => \"A new visitor!\"}\n)\n```\n\nThe V1 `amber g socket` shortcut is not a command in the standalone V2 CLI.\nCreate the socket struct explicitly, generate channels with `amber generate\nchannel`, and cover the handshake and authorization behavior with specs."}