> For the complete documentation index, see [llms.txt](https://mazeframework.gitbook.io/maze/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mazeframework.gitbook.io/maze/guides/websockets/sockets.md).

# Sockets

## Introduction

Socket structs are the objects that are stored in memory per connection and retain the persistent communication.

Sockets 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.

An `Maze::WebSockets::ClientSocket` instance has both `cookies` and `session` getters and are available from within the `on_connect` method.

Socket structs also map topics to the channels they will connect with.

## Example Usage

A socket can be generated by calling `maze g socket ChatSocket`

```ruby
struct ChatSocket < Maze::WebSockets::ClientSocket
  channel "chat_room:*", ChatRoomChannel

  def on_connect
    # self.session and self.cookies available here
    # do authentication here like
    # !self.session[:user_id].nil?

    # returning true accept all connections
    true
  end
end
```

## Send messages from controllers (or anywhere else)

`Maze::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.

```ruby
class HomeController < ApplicationController
  def index
    ChatSocket.broadcast("message", "chat_room:123", "message_new", {"message" => "A new visitor!"})
    render("index.slang")
  end
end
```
