{"title":"WebSocket Chat","description":"","section":"cookbook","version":"v1.5","path":"cookbook/websocket-chat","canonical_url":"https://amberframework.org/docs/v1.5/cookbook/websocket-chat","markdown_url":"https://amberframework.org/docs/v1.5/cookbook/websocket-chat.md","inherited":true,"content_markdown":"# WebSocket Chat\n\nThis recipe will help you to setup a basic WebSocket chat in your application.\n\n{% hint style=\"warning\" %}\nFirst you need an amber project generated with [Amber CLI](../guides/create-new-app.md) or [from scratch](from-scratch.md).\n{% endhint %}\n\n{% code-tabs %}\n{% code-tabs-item title=\"src/channels/chat\\_room\\_channel.cr\" %}\n```crystal\nclass ChatRoomChannel < Amber::Websockets::Channel\n  def handle_message(client_socket, msg)\n    rebroadcast!(msg)\n  end\nend\n```\n{% endcode-tabs-item %}\n{% endcode-tabs %}\n\nThen setup your socket file:\n\n{% code-tabs %}\n{% code-tabs-item title=\"src/sockets/chat\\_socket.cr\" %}\n```crystal\nstruct ChatSocket < Amber::WebSockets::ClientSocket\n  channel \"chat_room:*\", ChatRoomChannel\n\n  def on_connect\n    # returning true accept all connections\n    # you can use authentication here\n    true\n  end\nend\n```\n{% endcode-tabs-item %}\n{% endcode-tabs %}\n\nThen add the `websocket` verb in your routes file:\n\n{% code-tabs %}\n{% code-tabs-item title=\"config/routes.cr\" %}\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{% endcode-tabs-item %}\n{% endcode-tabs %}\n\nFinally you will require an [Amber JavaScript Client](../guides/websockets/javascript-client.md) to connect with your server:\n\n{% hint style=\"info\" %}\nYou can get `amber.min.js` from `lib/amber/assets/js/amber.min.js`\n{% endhint %}\n\n{% code-tabs %}\n{% code-tabs-item title=\"public/index.html\" %}\n```markup\n<script src=\"/public/amber.min.js\"></script>\n<script>\nlet socket = new Amber.Socket('/chat');\n\nsocket.connect().then(function() {\n    let channel = socket.channel('chat_room:hello');\n\n    channel.join();\n\n    channel.push('message_new', {\n      message: \"Hello Amber from WebSocket Client!\"\n    });\n\n    channel.on('message_new', function(payload) {\n      console.log(payload);\n    });\n});\n</script>\n```\n{% endcode-tabs-item %}\n{% endcode-tabs %}\n\n{% hint style=\"warning\" %}\nTo serve static files you must enable `:static` routes, please see [pipelines](../guides/routing/pipelines.md).\n{% endhint %}\n\nAlso see more detailed information about this in[ ](../guides/controllers/cookies.md)[WebSockets](../guides/websockets/)."}