# Channels ## Introduction All 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: * `handle_joined` - Called when a user joins a channel. * `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. * `handle_leave` - Called when a user leaves the channel. ## Example Usage A channel can be generated by calling `amber g channel ChatRoom`. ```ruby class ChatRoomChannel < Amber::Websockets::Channel # optional # Authorization can happen here def handle_joined(client_socket, message) # channel join related functionality # if client_socket.session[:user_id] != message["payload"]["user_id"] # client_socket.disconnect! # end end # required def handle_message(client_socket, msg) rebroadcast!(msg) end # optional def handle_leave(client_socket) # channel leave functionality end end ``` ## What happens when a user joins? The `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. This method allows you to run any logic needed to authorize who should be connected to a channel. This is also a great way to send out a `#{name} has joined the chat!` message to all those currently listening to the channel. ## How are messages broadcasted? Whenever a user sends a message that is broadcasted through the JavaScript `channel.push` function, the `handle_message` method is invoked. Here the message is then rebroadcasted to all those who are connected to the channel. The message is then transmitted through the `channel.on('message_new')` listener in the JavaScript. Before the message gets broadcast, here is where you would want to insert records into your database, if you wanted to keep a history of messages sent or received. ## What happens when a user leaves? When a user leaves the web page that currently has an established socket connection, the connection breaks and triggers a message to be sent on 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 be sent out to all connected clients.