{"title":"Sockets","description":"","section":"guides/websockets","version":"v1.5","path":"guides/websockets/sockets","canonical_url":"https://amberframework.org/docs/v1.5/guides/websockets/sockets","markdown_url":"https://amberframework.org/docs/v1.5/guides/websockets/sockets.md","inherited":true,"content_markdown":"# Sockets\n\n## Introduction\n\nSocket structs are the objects that are stored in memory per connection and retain the persistent communication.\n\nSockets define one public method on\\_connect which can contain functionality that should run when a user connects, including authentication. This methods should return a Bool. If `true` the socket will remain open. If `false` the socket will be closed immediately.\n\nAn `Amber::WebSockets::ClientSocket` instance has both `cookies` and `session` getters and are available from within the `on_connect` method.\n\nSocket structs also map topics to the channels they will connect with.\n\n## Example Usage\n\nA socket can be generated by calling `amber g socket Chat`\n\n```crystal\nstruct ChatSocket < Amber::WebSockets::ClientSocket\n  channel \"chat_room:*\", ChatRoomChannel\n\n  def on_connect\n    # self.session and self.cookies available here\n    # do authentication here like\n    # !self.session[:user_id].nil?\n\n    # returning true accept all connections\n    true\n  end\nend\n```\n\n## Add a new Route\n\nA new route needs to be added so that a handshake can be established with the server. Notice how after `\\chat`, the struct `ChatSocket` that was created \nabove is mapped to that route.\n\n```crystal\nAmber::Server.configure do |app|\n  pipeline :web do\n    # pipelines...\n  end\n\n  routes :web do\n    # other routes,,,\n    websocket \"/chat\", ChatSocket\n  end\nend\n```\n\n## Send messages from controllers \\(or anywhere else\\)\n\n`Amber::WebSockets::ClientSocket` provides a public class method `broadcast` for publishing messages to all subscribers of a topic from within controllers or anywhere else in your application.\n\n```crystal\nclass HomeController < ApplicationController\n  def index\n    ChatSocket.broadcast(\"message\", \"chat_room:123\", \"message_new\", {\"message\" => \"A new visitor!\"})\n    render(\"index.slang\")\n  end\nend\n```"}