### Set up Django Environment Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/tutorial/backend.md Creates a virtual environment, installs Django, and starts a new Django project. ```bash python3 -m venv env ./env/bin/activate python -m pip install Django python -m django --version django-admin startproject app mv app backend ``` -------------------------------- ### Local PostgreSQL Docker Setup Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/pro/access_revoke.md Quickly start a local PostgreSQL database instance using Docker for testing or development purposes. ```bash docker run -it --rm -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=pass -p 5432:5432 postgres:15 ``` -------------------------------- ### Client-side Subscription with Token Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2022-07-29-101-way-to-subscribe.md Example of creating a new subscription with a pre-fetched token. This is useful for initial subscription setup. ```javascript const token = await getSubscriptionToken('personal:17'); const sub = centrifuge.newSubscription('personal:17', { token: token }); sub.on('publication', function(ctx) { console.log(ctx.data); }); sub.subscribe(); ``` -------------------------------- ### Install Protobuf and gRPC Plugins Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2024-03-18-stream-loki-logs-to-browser-with-websocket-to-grpc-subscriptions.md Install the necessary tools for generating Go code from Protobuf definitions. ```bash go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest ``` -------------------------------- ### Connect to PostgreSQL Database Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/tutorial/tips_and_tricks.md Connect to the PostgreSQL database used in the example. Run this command from the root of the example repository. ```bash docker compose exec db psql postgresql://grandchat:grandchat@localhost:5432/grandchat ``` -------------------------------- ### Separate Redis for Broker and Presence Manager Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/engines.md Example configuration using distinct Redis instances for the broker and presence manager to distribute load or optimize setups. ```json { "broker": { "enabled": true, "type": "redis", "redis": { "address": "127.0.0.1:6379" } }, "presence_manager": { "enabled": true, "type": "redis", "redis": { "address": "127.0.0.1:6380" } } } ``` -------------------------------- ### Build AI Context Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/README.md An example command for building AI context, specifying documentation paths and descriptions for various project components. ```bash npm run build-context -- ./docs/faq "Centrifugo FAQ" ../centrifugo/config.default.json "Centrifugo default JSON configuration" ../centrifuge-js/src "centrifuge-js SDK source code (Javascript)" ../centrifuge-dart/lib "centrifuge-dart SDK source code (Dart)" ``` -------------------------------- ### Install Dependencies Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/tutorial/frontend.md Installs the necessary Node.js dependencies for the frontend project after it has been created. ```bash cd frontend npm install ``` -------------------------------- ### Start Local Development Server Source: https://github.com/centrifugal/centrifugal.dev/blob/main/README.md Starts a local development server for the website. Changes are reflected live without server restarts. ```bash yarn start ``` -------------------------------- ### Example Subscription Token Output Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/channel_token_auth.md Example output from the gensubtoken CLI command, showing a generated JWT. ```text HMAC SHA-256 JWT for user "123722" and channel "channel" with expiration TTL 168h0m0s: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM3MjIiLCJleHAiOjE2NTU0NDg0MzgsImNoYW5uZWwiOiJjaGFubmVsIn0.JyRI3ovNV-abV8VxCmZCD556o2F2mNL1UoU58gNR-uI ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/configuration.md Example of a Centrifugo configuration file in JSON format. ```json { "client": { "allowed_origins": [ "https://mysite1.com", "https://mysite2.com" ] }, "prometheus": { "enabled": true } } ``` -------------------------------- ### Engage with Centrifugo Project Links Source: https://github.com/centrifugal/centrifugal.dev/blob/main/design.html This interactive prompt provides links to get started, read full documentation, and clone the Git repository. ```text [▶ get_started()](#) [read_docs --full](#) [git clone .](#) ``` -------------------------------- ### Install Django Rest Framework Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/tutorial/backend.md Installs Django Rest framework and updates the requirements.txt file. ```bash pip install djangorestframework==3.14.0 pip freeze > requirements.txt ``` -------------------------------- ### Example Container Log Output Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2021-12-14-laravel-multi-room-chat-tutorial.md This is an example of the expected log output from the application container after a successful launch and database seeding. ```text ...\napp | Database seeding completed successfully.\napp | [10-Dec-2021 12:25:05] NOTICE: fpm is running, pid 112\napp | [10-Dec-2021 12:25:05] NOTICE: ready to handle connections ``` -------------------------------- ### Install Gunicorn Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/tutorial/backend.md Installs the Gunicorn web server and updates the requirements.txt file. ```bash pip install gunicorn==21.2.0 pip freeze > requirements.txt ``` -------------------------------- ### Array of Objects Configuration Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/configuration.md Example of setting an array of objects in the config.json file for options like channel namespaces. ```json { "channel": { "namespaces": [ {"name": "ns1"}, {"name": "ns2"} ] } } ``` -------------------------------- ### Start Project with Docker Compose Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2021-12-14-laravel-multi-room-chat-tutorial.md Run this command to start the application using Docker Compose. It will download necessary images and set up the environment. ```bash docker compose up ``` -------------------------------- ### TLS Configuration Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/tls.md Example of how to configure TLS settings in a JSON configuration file. This snippet shows enabling TLS and specifying certificate and key files. ```json { "unified_proxy": { "grpc": { "tls": { "enabled": true, "cert_pem_file": "/path/to/cert.pem", "key_pem_file": "/path/to/key.pem" } } } } ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/centrifugal/centrifugal.dev/blob/main/README.md Installs project dependencies using Yarn. This is the first step before running any other commands. ```bash yarn install ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2025-04-28-websocket-real-time-leaderboard.md Navigate to the newly created web directory and install the required npm packages: centrifuge for real-time communication, motion for animations, and bootstrap for styling. ```bash cd web npm install centrifuge motion bootstrap ``` -------------------------------- ### Start Toxiproxy Server Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2022-12-20-improving-redis-engine-performance.md Starts the Toxiproxy server, which is used to simulate network conditions like latency. ```bash toxyproxy-server ``` -------------------------------- ### TLS Server Configuration Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/configuration.md Example of configuring TLS settings for the HTTP server in Centrifugo's configuration file. ```json { "http_server": { "tls": { "enabled": true, "cert_pem": "/path/to/cert.pem", "key_pem": "/path/to/key.pem" } } } ``` -------------------------------- ### Go GRPC API JWT Authentication Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/pro/server_api_auth.md Example demonstrating how to create a gRPC context with the 'authorization' metadata for authenticated API calls in Go. ```go import ( "context" "google.golang.org/grpc" "google.golang.org/grpc/metadata" ) // Create context with authorization metadata md := metadata.New(map[string]string{ "authorization": "Bearer " + token, }) ctx := metadata.NewOutgoingContext(context.Background(), md) // Make GRPC API call with authenticated context response, err := client.Publish(ctx, &api.PublishRequest{ Channel: "chat", Data: []byte(`{"text": "hello"}`), }) ``` -------------------------------- ### Filter: String Starts With Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/publication_filtering.md Example of a 'starts with' filter. Matches if the 'ticker' tag begins with 'AA'. ```json {"key": "ticker", "cmp": "sw", "val": "AA"} ``` -------------------------------- ### Get User Status Response (No Active Info) Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/pro/user_status.md Example JSON response when a user is known but their last active time is not available. ```json { "result":{ "statuses":[ { "user":"42" } ] } } ``` -------------------------------- ### Setup Development Environment Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/tutorial/scale.md Orchestrates the creation of users, rooms, and populates rooms with members to set up a development environment for testing. ```python def setup_dev(): create_users(100_000) r1 = create_room('Centrifugo') fill_room(r1.pk, 100_000) r2 = create_room('Movies') fill_room(r2.pk, 10_000) r3 = create_room('Programming') fill_room(r3.pk, 1_000) r4 = create_room('Football') fill_room(r4.pk, 100) ``` -------------------------------- ### Get User Status Response (Active) Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/pro/user_status.md Example JSON response when status information is available for a user, including 'active' and 'online' timestamps. ```json { "result":{ "statuses":[ { "user":"42", "active":1627107289, "online":1627107289 } ] } } ``` -------------------------------- ### Initialize React Application Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2025-04-28-websocket-real-time-leaderboard.md Use create-react-app to scaffold a new React project for the leaderboard frontend. This command sets up the basic project structure and necessary build tools. ```bash npx create-react-app web ``` -------------------------------- ### Start Benthos Instance Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2023-08-19-asynchronous-message-streaming-to-centrifugo-with-benthos.md Launches a Benthos instance using the specified configuration file. ```bash benthos -c config.yaml ``` -------------------------------- ### Django Development Server Output Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2021-11-04-integrating-with-django-building-chat-application.md This is an example of the output seen in the terminal when the Django development server starts. It indicates system checks and server status. ```bash Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python3 manage.py migrate' to apply them. October 21, 2020 - 18:49:39 Django version 3.1.2, using settings 'mysite.settings' Starting development server at http://localhost:8000/ Quit the server with CONTROL-C. ``` -------------------------------- ### HAProxy Configuration for Redis Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/engines.md Example HAProxy configuration to balance traffic to Redis instances. This setup allows Centrifugo to connect to a single HAProxy address. ```haproxy listen redis server redis-01 127.0.0.1:6380 check port 6380 check inter 2s weight 1 inter 2s downinter 5s rise 10 fall 2 server redis-02 127.0.0.1:6381 check port 6381 check inter 2s weight 1 inter 2s downinter 5s rise 10 fall 2 backup bind *:16379 mode tcp option tcpka option tcplog option tcp-check tcp-check send PING\r\n tcp-check expect string +PONG tcp-check send info\ replication\r\n tcp-check expect string role:master tcp-check send QUIT\r\n tcp-check expect string +OK balance roundrobin ``` -------------------------------- ### HTTP Proxy Configuration Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/proxy.md Example configuration for enabling and setting up an HTTP proxy for client connect events. Use 'http://' or 'https://' in the endpoint to specify HTTP protocol. ```json { "client": { "proxy": { "connect": { "enabled": true, "endpoint": "https://your_backend/centrifugo/connect" } } } } ``` -------------------------------- ### Get Channel History with Limit and Since Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/transports/client_api.md Retrieve a limited number of publications from a channel's history, starting from a specific offset and epoch. Useful for fetching messages since a known point. ```javascript const resp = await subscription.history({limit: 10, since: {offset: 0, epoch: '...'}}); console.log(resp.publications); ``` -------------------------------- ### Initialize Node.js Project Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2021-10-18-integrating-with-nodejs.md Initializes a new Node.js project. Run this command in your project directory. ```bash npm init ``` -------------------------------- ### Reusing Redis Engine for Rate Limiting Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/pro/rate_limiting.md Configuration example demonstrating how to reuse the existing Centrifugo Redis engine for rate limiting instead of defining a separate Redis configuration. This simplifies setup when Redis is already configured for the engine. ```json { "engine": { "redis": { "address": "localhost:6379" }, "type": "redis" }, "client": { "rate_limit": { "redis_user_command": { "enabled": true, "redis": { "reuse_from_engine": true } } } } } ``` -------------------------------- ### Iterate Centrifugo History Stream in Go Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2021-08-31-hello-centrifugo-v3.md This Go example demonstrates how to iterate over a Centrifugo channel's history stream using the gocent library. It shows pagination in both forward and reverse directions, starting from the beginning or end of the stream, and handling missed messages. ```go import ( "context" "log" "github.com/centrifugal/gocent" ) func main() { // ... other setup ... ctx := context.Background() c := gocent.New(gocent.Config{ // ... config ... }) channel := "some-channel" // Iterate by 10. limit := 10 // Paginate in reversed order first, then invert it. reverse := true // Start with nil StreamPosition, then fill it with value while paginating. var sp *gocent.StreamPosition for { historyResult, err := c.History( ctx, channel, gocent.WithLimit(limit), gocent.WithReverse(reverse), gocent.WithSince(sp), ) if err != nil { log.Fatalf("Error calling history: %v", err) } for _, pub := range historyResult.Publications { log.Println(pub.Offset, "=>", string(pub.Data)) sp = &gocent.StreamPosition{ Offset: pub.Offset, Epoch: historyResult.Epoch, } } if len(historyResult.Publications) < limit { // Got all pubs, invert pagination direction. reverse = !reverse log.Println("end of stream reached, change iteration direction") } } } ``` -------------------------------- ### Install Centrifuge-JS SDK Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/tutorial/centrifugo.md Install the Centrifugo JavaScript SDK using npm. ```bash npm install centrifuge ``` -------------------------------- ### Comprehensive Example in YAML Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/pro/draft_client_publications.md The same comprehensive configuration as above, but presented in YAML for improved readability. It includes schema definition, JQ transformation, and client info exclusion. ```yaml schemas: - name: reaction definition: | { "type": "object", "properties": { "emoji": {"type": "string"}, "message_id": {"type": "string"} }, "required": ["emoji", "message_id"] } channel: patterns: true namespaces: - name: room_chat_reactions pattern: /rooms/:room_id/reactions publication_data_format: json client_publication: schemas: [reaction] transform: enabled: true engine: jq jq: program: | { data: { emoji: .data.emoji, message_id: .data.message_id, user_id: .user }, tags: { room: .vars.room_id, user: .user }, idempotency_key: (.user + ":" + .data.message_id + ":" + .data.emoji) } exclude_client_info: true allow_publish_for_subscriber: true ``` -------------------------------- ### Duration Type Examples Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/configuration.md Examples of specifying time durations in Centrifugo configuration. ```js "1000ms" // 1000 milliseconds "1s" // 1 second "12h" // 12 hours "720h" // 30 days ``` -------------------------------- ### Run Setup Function Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/tutorial/scale.md Python code to be executed within the Django shell to call the setup_dev function and prepare the test environment. ```python from app.utils import setup_dev setup_dev() ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/configuration.md An example of a Centrifugo configuration file in TOML format. It mirrors the JSON example, showing settings for client JWT secret, allowed origins, and HTTP API key. ```toml [client] allowed_origins = [ "http://localhost:3000" ] [client.token] hmac_secret_key = "" [http_api] key = "" ``` -------------------------------- ### Provide Initial Subscriptions on Connect Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2021-01-15-centrifuge-intro.md Configure initial channel subscriptions when a client connects. This is done once during connection establishment. ```go node.OnConnecting(func(ctx context.Context, e centrifuge.ConnectEvent) (centrifuge.ConnectReply, error) { return centrifuge.ConnectReply{ Subscriptions: map[string]centrifuge.SubscribeOptions{ "example": {}, }, }, nil }) ``` -------------------------------- ### Publication Tags Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/publication_filtering.md An example of tags that can be attached to a publication. These tags are used for filtering. ```json { "ticker": "AAPL", "source": "NASDAQ", "price": "150.25", "category": "tech", "volume": "1000" } ``` -------------------------------- ### Build Centrifugo from Source Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/getting-started/installation.md Clone the repository, navigate to the directory, build the executable, and run Centrifugo. Requires Go to be installed. ```bash git clone https://github.com/centrifugal/centrifugo.git cd centrifugo go build ./centrifugo ``` -------------------------------- ### List Kafka Topics Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/tutorial/tips_and_tricks.md List all available Kafka topics. This command is run from the root of the example repository. ```bash docker compose exec kafka kafka-topics --bootstrap-server kafka:9092 --list ``` -------------------------------- ### Example ClickHouse Query Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/pro/analytics.md An example SQL query to select all operations from the centrifugo.operations table in ClickHouse. ```sql SELECT * FROM centrifugo.operations ``` -------------------------------- ### Accept QUIC Connections Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2020-10-16-experimenting-with-quic-transport.md Implements the Run method to accept incoming QUIC client connections using quic.Listener and handle each session in a goroutine. ```go // Run server. func (s *WebTransportServerQuic) Run() error { listener, err := quic.ListenAddr(s.config.ListenAddr, s.generateTLSConfig(), nil) if err != nil { return err } for { sess, err := listener.Accept(context.Background()) if err != nil { return err } log.Printf("session accepted: %s", sess.RemoteAddr().String()) go func() { defer func() { _ = sess.CloseWithError(0, "bye") log.Println("close session") }() s.handleSession(sess) }() } } func (s *WebTransportServerQuic) handleSession(sess quic.Session) { // Not implemented yet. } ``` -------------------------------- ### Subscribe Push Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/transports/uni_client_protocol.md Example of a 'subscribe' push message, sent when the connection is subscribed to a channel during its lifetime. ```json { "channel":"test", "subscribe":{} } ``` -------------------------------- ### JWKS Provider Configuration for Connection and Subscription Tokens Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/pro/client_authentication.md Example configuration showing how to set up JWKS providers for both initial client connections and subsequent subscription tokens. Note that `meta_from_claim` is not supported for subscription tokens. ```json { "client": { "token": { "jwks": { "enabled": true, "providers": [{ "name": "auth0_connection", "enabled": true, "endpoint": "https://tenant.auth0.com/.well-known/jwks.json", "issuer": "https://tenant.auth0.com/", "audience": "centrifugo" }] } }, "subscription_token": { "enabled": true, "jwks": { "enabled": true, "providers": [{ "name": "subscription_identity", "enabled": true, "endpoint": "https://tenant.example.com/.well-known/jwks.json", "issuer": "https://tenant.example.com", "audience": "centrifugo" }] } } } } ``` -------------------------------- ### Create Project Directory Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/tutorial/backend.md Initializes the project directory and creates a docker-compose.yml file. ```bash mkdir grand-chat-tutorial cd grand-chat-tutorial touch docker-compose.yml ``` -------------------------------- ### Unsubscribe Push Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/transports/uni_client_protocol.md Example of an 'unsubscribe' push message, sent when the connection is unsubscribed from a channel during its lifetime. ```json { "channel":"test", "unsubscribe":{} } ``` -------------------------------- ### JSON Reply with Error Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/transports/client_protocol.md An example of a reply message that indicates an error occurred during command processing. ```json {"id": 1, "error": {"code": 100, "message": "internal server error"}} ``` -------------------------------- ### GRPC Proxy Configuration Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/proxy.md Example configuration for enabling and setting up a GRPC proxy for client connect events. Use 'grpc://' in the endpoint to specify GRPC protocol. ```json { "client": { "proxy": { "connect": { "enabled": true, "endpoint": "grpc://your_backend:9000" } } } } ``` -------------------------------- ### Client Connection Lifecycle Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/transports/client_api.md Demonstrates creating a Centrifuge client, setting up callbacks for connection state changes, and initiating a connection. Use this to observe and react to connection events. ```javascript const client = new Centrifuge('ws://localhost:8000/connection/websocket', {}); client.on('connecting', function(ctx) { console.log('connecting', ctx); }); client.on('connected', function(ctx) { console.log('connected', ctx); }); client.on('disconnected', function(ctx) { console.log('disconnected', ctx); }); client.connect(); ``` ```dart final onEvent = (dynamic event) { print('client event> $event'); }; final client = centrifuge.createClient( 'ws://localhost:8000/connection/websocket', centrifuge.ClientConfig(), ); client.connecting.listen(onEvent); client.connected.listen(onEvent); client.disconnected.listen(onEvent); await client.connect(); ``` ```swift import SwiftCentrifuge class ClientDelegate : NSObject, CentrifugeClientDelegate { func onConnecting(_ c: CentrifugeClient, _ e: CentrifugeConnectingEvent) { print("connecting", e.code, e.reason) } func onConnected(_ client: CentrifugeClient, _ e: CentrifugeConnectedEvent) { print("connected with id", e.client) } func onDisconnected(_ client: CentrifugeClient, _ e: CentrifugeDisconnectedEvent) { print("disconnected", e.code, e.reason) } } let config = CentrifugeClientConfig() let endpoint = "ws://localhost:8000/connection/websocket" let client = CentrifugeClient(endpoint: endpoint, config: config, delegate: ClientDelegate()) client.connect() ``` ```java EventListener listener = new EventListener() { @Override public void onConnected(Client client, ConnectedEvent event) { System.out.println("connected"); } @Override public void onConnecting(Client client, ConnectingEvent event) { System.out.printf("connecting: %s%n", event.getReason()); } @Override public void onDisconnected(Client client, DisconnectedEvent event) { System.out.printf("disconnected %d %s", event.getCode(), event.getReason()); } }; Options opts = new Options(); Client client = new Client("ws://localhost:8000/connection/websocket", opts, listener); client.connect(); ``` ```go client := centrifuge.NewJsonClient( "ws://localhost:8000/connection/websocket", centrifuge.Config{}, ) defers client.Close() client.OnConnecting(func(e centrifuge.ConnectingEvent) { log.Printf("Connecting - %d (%s)", e.Code, e.Reason) }) client.OnConnected(func(e centrifuge.ConnectedEvent) { log.Printf("Connected with ID %s", e.ClientID) }) client.OnDisconnected(func(e centrifuge.DisconnectedEvent) { log.Printf("Disconnected: %d (%s)", e.Code, e.Reason) }) _ = client.connect() ``` -------------------------------- ### Start Nats Server Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/engines.md This command starts the Nats server. Ensure it is running before configuring Centrifugo to use it. ```bash $ nats-server [3569] 2020/07/08 20:28:44.324269 [INF] Starting nats-server version 2.1.7 [3569] 2020/07/08 20:28:44.324400 [INF] Git commit [not set] [3569] 2020/07/08 20:28:44.325600 [INF] Listening for client connections on 0.0.0.0:4222 [3569] 2020/07/08 20:28:44.325612 [INF] Server id is NDAM7GEHUXAKS5SGMA3QE6ZSO4IQUJP6EL3G2E2LJYREVMAMIOBE7JT4 [3569] 2020/07/08 20:28:44.325617 [INF] Server is ready ``` -------------------------------- ### Comprehensive Example with JQ Transformation and Schema Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/pro/draft_client_publications.md A complete configuration example combining schema definition, JQ transformation for reactions, and excluding client info. It defines a 'reaction' schema and applies a transformation to enrich publication data. ```json { "schemas": [ { "name": "reaction", "type": "jsonschema_draft_2020_12", "definition": "{\"type\": \"object\", \"properties\": {\"emoji\": {\"type\": \"string\"},\"message_id\": {\"type\": \"string\"}}, \"required\": [\"emoji\",\"message_id\"], \"additionalProperties\": false}" } ], "channel": { "patterns": true, "namespaces": [ { "name": "room_chat_reactions", "pattern": "/rooms/:room_id/reactions", "publication_data_format": "json", "client_publication": { "schemas": ["reaction"], "transform": { "enabled": true, "engine": "jq", "jq": { "program": "{data: {emoji: .data.emoji, message_id: .data.message_id, user_id: .user}, tags: {room: .vars.room_id, user: .user}, idempotency_key: (.user + ":" + .data.message_id + ":" + .data.emoji)}" } }, "exclude_client_info": true }, "allow_publish_for_subscriber": true } ] } } ``` -------------------------------- ### Initialize Subscription with Dynamic Token Callback Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/transports/client_api.md This example demonstrates how to initialize a subscription using a `getToken` callback function. The SDK will invoke this function to fetch a JWT token dynamically, which is essential for token expiration and refresh scenarios. Ensure your backend endpoint is correctly set up to provide tokens. ```javascript async function getToken(ctx) { // Fetch your application backend. const res = await fetch('http://localhost:8000/centrifugo/subscription_token', { method: 'POST', headers: new Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ channel: ctx.channel }) }); if (!res.ok) { if (res.status === 403) { // Return special error to not proceed with token refreshes, // client will be disconnected. throw new Centrifuge.UnauthorizedError(); } // Any other error thrown will result into token refresh re-attempts. throw new Error(`Unexpected status code ${res.status}`); } const data = await res.json(); return data.token; } const client = new Centrifuge('ws://localhost:8000/connection/websocket', {}); const sub = centrifuge.newSubscription(channel, { token: 'JWT-GENERATED-ON-BACKEND-SIDE', // Optional, getToken is enough. getToken: getToken }); sub.subscribe(); ``` -------------------------------- ### Centrifugo Server Start Command Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2021-10-18-integrating-with-nodejs.md Command to start the Centrifugo server using a specified configuration file. ```bash ./centrifugo -c config.json ``` -------------------------------- ### Create Django Project Source: https://github.com/centrifugal/centrifugal.dev/blob/main/blog/2021-11-04-integrating-with-django-building-chat-application.md Initializes a new Django project named 'mysite'. This command creates the basic directory structure for a Django application. ```bash django-admin startproject mysite ``` -------------------------------- ### Install Centrifugo PRO RPM Package Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/pro/install_and_run.md Downloads and installs the Centrifugo PRO RPM package on CentOS systems. ```shell wget https://github.com/centrifugal/centrifugo-pro/releases/download/v6.8.1/centrifugo-pro-6.8.1-0.x86_64.rpm sudo yum install centrifugo-pro-6.8.1-0.x86_64.rpm ``` -------------------------------- ### Override Object Example Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/server_api.md Example of an override object used in subscribe requests to dynamically change channel options. ```json { "presence": {"value": true}, "join_leave": {"value": false} } ``` -------------------------------- ### Generate Configuration Documentation Source: https://github.com/centrifugal/centrifugal.dev/blob/main/docs/server/console_commands.md Starts a web server to display documentation for all Centrifugo configuration options. Can also output Markdown to STDOUT or filter by a specific section. ```bash centrifugo configdoc ``` ```bash centrifugo configdoc --markdown ``` ```bash centrifugo configdoc --section=consumers ```