{"title":"Channels","description":"","section":"guides/websockets","version":"v1.5","path":"guides/websockets/channels","canonical_url":"https://amberframework.org/docs/v1.5/guides/websockets/channels","markdown_url":"https://amberframework.org/docs/v1.5/guides/websockets/channels.md","inherited":true,"content_markdown":"# Channels\n\n## Introduction\n\nAll messages are routed through channels, and channel topics are where clients subscribe to listen for new messages. Channels define 3 public methods that can be used:\n\n* `handle_joined` - Called when a user joins a channel.\n* `handle_message` - Called when a user sends a message to a channel.  A common message handler will simply rebroadcast the message to the other subscribers with `rebroadcast!` method.\n* `handle_leave` - Called when a user leaves the channel.\n\n## Example Usage\n\nA channel can be generated by calling `amber g channel ChatRoom`.\n\n```crystal\nclass ChatRoomChannel < Amber::Websockets::Channel\n\n  # optional\n  # Authorization can happen here  \n  def handle_joined(client_socket, message)\n    # channel join related functionality\n    # if client_socket.session[:user_id] != message[\"payload\"][\"user_id\"]\n    #   client_socket.disconnect!\n    # end\n  end\n\n  # required\n  def handle_message(client_socket, msg)\n    rebroadcast!(msg)\n  end\n\n  # optional\n  def handle_leave(client_socket)\n    # channel leave functionality    \n  end\nend\n```\n\n## What happens when a user joins?\n\nThe `handle_joined` method is invoked when a user lands on a web page that has a `new Amber.Socket` established through the JavaScript on it.\nThis method allows you to run any logic needed to authorize who should be connected to a channel. This is also a great \nway to send out a `#{name} has joined the chat!` message to all those currently listening to the channel.\n\n## How are messages broadcasted?\n\nWhenever a user sends a message that is broadcasted through the JavaScript `channel.push` function, the `handle_message` method is invoked. \nHere the message is then rebroadcasted to all those who are connected to the channel. The message is then transmitted through the \n`channel.on('message_new')` listener in the JavaScript. Before the message gets broadcast, here is where you would want to insert records into your \ndatabase, if you wanted to keep a history of messages sent or received.\n\n## What happens when a user leaves?\n\nWhen a user leaves the web page that currently has an established socket connection, the connection breaks and triggers a message to be sent \non the servers side. The `handle_leave` method handles this in the channels class. Here is where a message such as `#{name} has left the chat!` could \nbe sent out to all connected clients."}