### Run Soketi Docker Image Source: https://docs.soketi.app/getting-started/installation/docker This command runs the default Debian-based Soketi Docker image, exposing the necessary ports for operation. It's a quick way to get Soketi up and running. ```docker docker run -p 6001:6001 -p 9601:9601 quay.io/soketi/soketi:1.4-16-debian ``` -------------------------------- ### Start Supervisor Daemon (Bash) Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps This command starts the Supervisor daemon manager. It's used to initialize and run Supervisor services. ```bash service supervisord start ``` -------------------------------- ### Install Dependencies with Composer Source: https://github.com/soketi/network-watcher This command installs project dependencies using Composer. It ignores platform requirements, which can be useful in certain deployment scenarios. The command also copies the environment example file to create a new .env file, essential for configuration. ```bash composer install --ignore-platform-reqs && cp .env.example .env ``` -------------------------------- ### Install Soketi CLI Globally via NPM Source: https://context7_llms Installs the Soketi CLI package globally on your system using NPM. This command requires Node.js LTS to be installed due to uWebSockets.js build limitations. After installation, the server can be started with the 'soketi start' command. ```bash npm install -g @soketi/soketi ``` -------------------------------- ### Run Distroless-based Soketi Docker Image Source: https://docs.soketi.app/getting-started/installation/docker This command utilizes a Distroless-based Soketi Docker image, which offers enhanced security by removing shells and other utilities. It's recommended for production environments. ```docker docker run -p 6001:6001 quay.io/soketi/soketi:1.0-16-distroless ``` -------------------------------- ### Troubleshooting Supervisor Configuration Error (Bash) Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps This command is used to start the Supervisor daemon but may result in an error if the configuration file is missing the necessary '[supervisord]' section. The error message provides a hint on how to get help. ```bash /usr/local/bin/supervisord -h ``` -------------------------------- ### Build and Run uWebSockets HelloWorldThreaded Source: https://alexhultman.medium.com/serving-100k-requests-second-from-a-fanless-raspberry-pi-4-over-ethernet-fdd2c2e05a1e This snippet demonstrates how to clone the uWebSockets repository, build the HelloWorldThreaded example, and run it. It's a prerequisite for performing load tests. Ensure you have C++ build tools installed. ```bash git clone --recursive https://github.com/uNetworking/uWebSockets cd uWebSockets make ./HelloWorldThreaded ``` -------------------------------- ### Start Soketi Server with .env File Configuration Source: https://docs.soketi.app/getting-started/environment-variables This code snippet illustrates how to start the Soketi server after configuring it via an .env file. Ensure the .env file is in the directory from which the soketi start command is executed. ```bash soketi start ``` -------------------------------- ### Supervisorctl Commands for Program Management Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps Within the `supervisorctl` interactive shell, various commands are available to control and monitor programs. These include starting, stopping, checking status, and viewing logs. ```bash help start idle stop idle tail idle tail idle stderr status quit ``` -------------------------------- ### Soketi Docker Image Tagging Convention Source: https://docs.soketi.app/getting-started/installation/docker Explains the naming convention for Soketi Docker images, which includes the Git version and Node.js version. This allows for specific version pinning or using the latest development branch. ```docker quay.io/soketi/soketi:[git_version]-[node_version] ``` -------------------------------- ### Supervisor Configuration Example (INI) Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps An example of a Supervisor configuration file directive to change the working directory before running a command. This is useful for resolving relative path issues within applications managed by Supervisor. ```ini directory=[some directory] ``` -------------------------------- ### Configure Soketi via JSON File Source: https://docs.soketi.app/getting-started/environment-variables This example shows how to configure Soketi using a JSON file. The file allows for detailed configuration, including enabling debug mode, setting the port, and defining app credentials with webhook configurations. The server is started using the --config flag. ```json { "debug": true, "port": 6002, "appManager.array.apps": [ { "id": "some-id", "key": "some-key", "secret": "some-secret", "webhooks": [ { "url": "https://...", "event_types": ["channel_occupied"] } ] } ] } ``` -------------------------------- ### Start Soketi Server with JSON Configuration File Source: https://docs.soketi.app/getting-started/environment-variables This command starts the Soketi server and specifies a custom configuration file using the --config flag. The provided path should point to the JSON configuration file. ```bash soketi start --config=/path/to/config.json ``` -------------------------------- ### Start Soketi Server Source: https://context7_llms Starts a Soketi server instance with default configuration using the NPM package. The server defaults to running on 127.0.0.1:6001 with predefined application credentials. ```bash soketi start ``` -------------------------------- ### Install Soketi via NPM Source: https://context7_llms Installs the Soketi package globally using NPM. Node.js LTS versions are recommended due to uWebSockets.js build limitations. ```bash npm install -g @soketi/soketi ``` -------------------------------- ### Enabling Soketi Webhook Batching (Command Line) Source: https://docs.soketi.app/advanced-usage/app-webhooks Command to start the Soketi server with webhook batching enabled. ```bash SOKETI_WEBHOOKS_BATCHING=1 soketi start ``` -------------------------------- ### uWebSockets Minimal HTTP Server Example Source: https://alexhultman.medium.com/serving-100k-requests-second-from-a-fanless-raspberry-pi-4-over-ethernet-fdd2c2e05a1e A minimal C++ example using uWebSockets to set up a basic HTTP server that responds with 'Hello world!' to all requests on port 3000. This snippet showcases the core functionality of the library for simple web serving. ```cpp uWS::App().get("/*", [] (auto *res, auto *req) { res->end("Hello world!"); }).listen(3000, [] (auto *listen_socket) { if (listen_socket) { std::cout << "Listening on port " << 3000 << std::endl; } }).run(); ``` -------------------------------- ### Install Build Dependencies for Soketi (Ubuntu) Source: https://context7_llms Installs necessary build tools and dependencies on Ubuntu for compiling Soketi, which relies on uWebSocket.js. This includes git, Python 3, gcc, and build-essential. These prerequisites are required if not using the Docker installation method. ```bash apt install -y git python3 gcc build-essential ``` -------------------------------- ### Basic ioredis Usage in Node.js Source: https://github.com/luin/ioredis Demonstrates the basic setup and usage of the ioredis client. It shows how to import the library and create a Redis instance, which can then be used to interact with a Redis server. ```javascript const Redis = require("ioredis"); // Create a Redis instance. ``` -------------------------------- ### Install Soketi CLI Dependencies (Ubuntu) Source: https://context7_llms Installs necessary dependencies for building Soketi via the CLI on Ubuntu systems. This includes Git, Python 3, GCC, and build essentials. ```bash apt install -y git python3 gcc build-essential ``` -------------------------------- ### ioredis Cluster Connection Example Source: https://github.com/luin/ioredis Establishes a connection to a Redis Cluster, allowing automatic sharding of data across multiple nodes. Includes basic set and get operations. ```javascript const Redis = require("ioredis"); const cluster = new Redis.Cluster([ { port: 6380, host: "127.0.0.1", }, { port: 6381, host: "127.0.0.1", }, ]); cluster.set("foo", "bar"); cluster.get("foo", (err, res) => { // res === 'bar' }); ``` -------------------------------- ### Install and Check Supervisor Status (Bash) Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps Installs the Supervisor package using apt and checks its operational status. This is the initial step to ensure the process manager is ready to use. ```bash sudo apt update && sudo apt install supervisor sudo systemctl status supervisor ``` -------------------------------- ### Start Soketi with Cluster Adapter Source: https://context7_llms This command starts the Soketi server using the Cluster driver for inter-node communication. It enables built-in scalability without requiring additional servers like Redis Pub/Sub. This method is ideal for deploying Soketi behind the same private network, especially with PM2 for multithreading. The primary limitation is that scaling is restricted to instances within the same network, as the protocol is tied to a shared hostname. ```bash SOKETI_ADAPTER_DRIVER=cluster soketi start ``` -------------------------------- ### Start Soketi with PM2 Source: https://context7_llms This command uses PM2, a process manager for Node.js applications, to start the Soketi server. It leverages the PM2-ready binary shipped with Soketi to manage the process, enabling features like clustering and horizontal scaling across multiple threads or instances. ```bash pm2 start soketi-pm2 -- start ``` -------------------------------- ### Install ioredis with npm Source: https://github.com/luin/ioredis Installs the ioredis package using npm. This is the primary step to include the Redis client in your Node.js project. ```bash npm install ioredis ``` -------------------------------- ### Configuring Soketi Webhook Batching Duration (Command Line) Source: https://docs.soketi.app/advanced-usage/app-webhooks Command to start the Soketi server with webhook batching enabled and a custom duration for event build-up. ```bash SOKETI_WEBHOOKS_BATCHING=1 SOKETI_WEBHOOKS_BATCHING_DURATION=1000 soketi start ``` -------------------------------- ### Install TypeScript Declarations for Node.js Source: https://github.com/luin/ioredis Installs the TypeScript type definitions for Node.js as a development dependency. This is recommended for TypeScript projects to get better type checking and autocompletion for Node.js APIs. ```bash npm install --save-dev @types/node ``` -------------------------------- ### Build and Run Soketi Docker Image Locally Source: https://github.com/soketi/soketi/pull/178 Commands to build the Soketi Docker image from the Dockerfile and run it locally. Verifies the server starts correctly by curling the health endpoint. ```bash docker build -t soketi . docker run -p 6001:6001 soketi curl localhost:6001 ``` -------------------------------- ### Install Ably PHP SDK Source: https://laravel.com/docs/8.x/broadcasting Installs the Ably PHP SDK using Composer, enabling event broadcasting through the Ably service. ```bash composer require ably/ably-php ``` -------------------------------- ### Using AWS SDK for JavaScript with Promises Source: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html This example illustrates how to interact with AWS services using Promises, which allows for cleaner asynchronous code management compared to callbacks. It shows how to create a service object and call a method, handling the response or errors. ```javascript const AWS = require('aws-sdk'); // Configure SDK (assuming credentials and region are set) AWS.config.update({ region: 'us-east-1' }); const s3 = new AWS.S3(); // Example: List S3 buckets using Promises async function listBuckets() { try { const data = await s3.listBuckets().promise(); console.log('Buckets:', data.Buckets); } catch (err) { console.error('Error listing buckets:', err); } } listBuckets(); ``` -------------------------------- ### Soketi Webhook Filtering Example (JavaScript) Source: https://docs.soketi.app/advanced-usage/app-webhooks Example illustrating JavaScript client subscriptions and how they would interact with the channel name filtering configuration. ```javascript // Won't trigger the webhook client.subscribe('chat-room'); client.subscribe('beta-chat-room'); client.subscribe('chat-room-app'); // Will trigger the webhook client.subscribe('beta-chat-room-app'); ``` -------------------------------- ### Reload and Update Supervisor Configurations Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps These commands inform Supervisor about new or changed program configurations and then apply those changes. Ensure the configuration directory exists before running these commands. ```bash sudo supervisorctl reread sudo supervisorctl update ``` -------------------------------- ### Start Soketi Server with Debug Enabled via CLI Source: https://context7_llms This command starts the Soketi server with the debug mode enabled directly from the command line. This is a quick way to enable debugging for development or troubleshooting purposes. ```bash DEBUG=1 soketi start ``` -------------------------------- ### Install Soketi Helm Chart Source: https://github.com/soketi/charts/tree/master/charts/soketi Installs or upgrades the soketi Helm chart to your Kubernetes cluster. This command deploys the soketi application with the specified version and allows for further customization via values.yaml. ```bash helm upgrade soketi \ --install \ --version=2.0.0 \ soketi/soketi ``` -------------------------------- ### Start Soketi with Cluster Driver Source: https://context7_llms This command initiates the Soketi server using the cluster adapter for private network scaling. It's recommended to use this with PM2 for multithreading in private networks. Ensure the ADAPTER_DRIVER environment variable is set. ```bash ADAPTER_DRIVER=cluster soketi start ``` -------------------------------- ### Install Laravel Echo and Pusher JS (NPM) Source: https://laravel.com/docs/8.x/broadcasting Installs the necessary Node.js packages for Laravel Echo and Pusher JS, which are required for client-side event listening. These packages are typically installed as development dependencies. ```bash npm install --save-dev laravel-echo pusher-js ``` -------------------------------- ### Run Network Watcher Command Source: https://github.com/soketi/network-watcher This command initiates the Network Watcher service using the Artisan command-line interface. It assumes the project is a Laravel application. This is the primary command to start the memory monitoring and management process. ```bash php artisan network:watch ``` -------------------------------- ### Configure Supervisor for a Program (INI) Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps Defines a Supervisor configuration file for a bash script. It specifies the command to run, whether to autostart and autorestart the program, and the locations for its standard output and error log files. ```ini [program:idle] command=/home/ubuntu/idle.sh autostart=true autorestart=true stderr_logfile=/var/log/idle.err.log stdout_logfile=/var/log/idle.out.log ``` -------------------------------- ### Connect to Redis with ioredis Source: https://github.com/luin/ioredis Demonstrates how to establish a connection to a Redis server using the ioredis library. This is a fundamental step before executing any Redis commands. It requires the 'ioredis' package to be installed. ```javascript const Redis = require('ioredis'); // Connect to Redis server on localhost:6379 const redis = new Redis(); // You can also specify connection options like password and database // const redis = new Redis({ // port: 6379, // Redis port // host: '127.0.0.1', // Redis host // username: 'default', // needs Redis >= 6 // password: 'my-redis-password', // db: 0, // Defaults to 0 // }); redis.on('connect', () => { console.log('Connected to Redis!'); }); redis.on('error', (err) => { console.error('Redis error:', err); }); ``` -------------------------------- ### Example of Internal Processing Time Calculation Source: https://context7_llms This example demonstrates how to apply the formula to calculate the internal processing time of Soketi based on provided benchmark data. It shows the server's ability to process messages quickly. ```plaintext INTERNAL_TIME = 90 - (42 * 2) = 90 - 84 = 6 ms ``` -------------------------------- ### Example Client Sign-in Event Data Source: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol Provides a concrete example of the `pusher:signin` event data, demonstrating how user authentication and additional user information are structured. The `user_data` is a JSON string containing user details like ID and name. ```json { "event": "pusher:signin", "data": { "auth": "::user::", "user_data": "{ \"id\": \"\", \"name\": \"Phil Leggetter\", \"twitter\": \"@leggetter\", \"blogUrl\":\"http://blog.pusher.com\" }" } } ``` -------------------------------- ### Install Pusher Channels PHP SDK Source: https://laravel.com/docs/8.x/broadcasting Installs the Pusher Channels PHP SDK using Composer, which is required for broadcasting events via Pusher Channels. ```bash composer require pusher/pusher-php-server ``` -------------------------------- ### PHP User Authentication Endpoint Example Source: https://pusher.com/docs/channels/server_api/authenticating-users This PHP snippet illustrates how to implement a user authentication endpoint for Pusher. It assumes you have a global `$user` object available with properties like `uid` and `name`. This code prepares user data, including ID, user info, and watchlist, for Pusher authentication. It's a basic example and requires integration with your specific user management system. ```php global $user; if ($user->uid) { $user_data = [ 'id' => (string) $user->uid, 'user_info' => [ 'name': $user->name, ], 'watchlist' => $user->wat ``` -------------------------------- ### View Program Output Log Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps This command displays the recent output from a program's standard output log file. It is useful for debugging and monitoring program activity. ```bash sudo tail /var/log/idle.out.log ``` -------------------------------- ### Run Distroless Soketi Docker Image Source: https://context7_llms This command demonstrates how to run a distroless-based Soketi Docker image. Distroless images offer enhanced security by minimizing the attack surface. This example exposes Soketi on port 6001. ```bash docker run -p 6001:6001 quay.io/soketi/soketi:0.34-16-distroless ``` -------------------------------- ### Set and Get Key-Value Pairs with ioredis Source: https://github.com/luin/ioredis Illustrates the basic usage of SET and GET commands to store and retrieve string values in Redis. This is a core functionality for key-value storage. It assumes a Redis connection has already been established. ```javascript async function setAndGet() { try { // Set a key-value pair await redis.set('mykey', 'myvalue'); console.log('Key set successfully.'); // Get the value of a key const value = await redis.get('mykey'); console.log('Value for mykey:', value); // Set a key with an expiration time (in seconds) await redis.set('temporarykey', 'some data', 'EX', 10); console.log('Temporary key set with expiration.'); } catch (err) { console.error('Error during set/get operation:', err); } } setAndGet(); ``` -------------------------------- ### Enter Supervisorctl Interactive Mode Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps Running `supervisorctl` without arguments launches an interactive shell for managing Supervisor programs. This mode allows for real-time control and status checks. ```bash sudo supervisorctl ``` -------------------------------- ### Configure Pusher PHP SDK Source: https://context7_llms Configure the Pusher PHP SDK to interact with soketi. This example sets up a basic connection using HTTP and specifies host, port, and encryption settings. For SSL, set 'scheme' to 'https' and 'useTLS' to true. ```php use Pusher\Pusher; $pusher = new Pusher('app-key', 'app-secret', 'app-id', [ 'host' => '127.0.0.1', 'port' => 6001, 'scheme' => 'http', 'encrypted' => true, 'useTLS' => false, ]); ``` -------------------------------- ### Add Helm Chart Repository Source: https://github.com/soketi/charts/tree/master/charts/soketi Adds the soketi Helm chart repository to your local Helm configuration. This command fetches the repository index and makes the charts available for installation. ```bash helm repo add soketi https://helm.soketi.app ``` -------------------------------- ### WebSocket Connection URL Example Source: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol Demonstrates the format of a WebSocket connection URL for Pusher Channels. It includes placeholders for scheme, cluster name, port, app key, and required query parameters like protocol, client, and version. ```websocket ws://ws-ap1.pusher.com:80/app/APP_KEY?client=js&version=7.0.3&protocol=5 ``` -------------------------------- ### Use Pub/Sub with ioredis Source: https://github.com/luin/ioredis Provides an example of how to implement publish-subscribe messaging using ioredis. This involves subscribing to channels and publishing messages to them, enabling real-time communication. ```javascript async function pubSubExample() { const subscriber = new Redis(); const publisher = new Redis(); // Subscribe to a channel await subscriber.subscribe('mychannel'); console.log('Subscribed to mychannel.'); subscriber.on('message', (channel, message) => { console.log(`Received message from ${channel}: ${message}`); }); // Publish a message to a channel after a delay setTimeout(async () => { await publisher.publish('mychannel', 'Hello from publisher!'); console.log('Published message to mychannel.'); }, 1000); // Don't forget to unsubscribe and quit when done // setTimeout(async () => { // await subscriber.unsubscribe('mychannel'); // subscriber.quit(); // publisher.quit(); // console.log('Unsubscribed and quit.'); // }, 5000); } pubSubExample(); ``` -------------------------------- ### Presence Channel Subscription Success Event Example Source: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol An example JSON payload illustrating the 'pusher_internal:subscription_succeeded' event. This showcases the nested structure of the 'data' field, including an array of user IDs, a hash mapping user IDs to their information, and the total user count. ```json { "event": "pusher_internal:subscription_succeeded", "channel": "presence-example-channel", "data": "{ \"presence\": { \"ids\": [\"11814b369700141b222a3f3791cec2d9\",\"71dd6a29da2a4833336d2a964becf820\"], \"hash\": { \"11814b369700141b222a3f3791cec2d9\": { \"name\":\"Phil Leggetter\", \"twitter\": \"@leggetter\" }, \"71dd6a29da2a4833336d2a964becf820\": { \"name\":\"Max Williams\", \"twitter\": \"@maxthelion\" } }, \"count\": 2 } }" } ``` -------------------------------- ### Create a Persistent Bash Script (Bash) Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps Creates a simple bash script that runs indefinitely, printing the current date to standard output and an error message to standard error every second. This script is used to demonstrate Supervisor's process management. ```bash #!/bin/bash while true do # Echo current date to stdout echo `date` # Echo 'error!' to stderr echo 'error!' >&2 sleep 1 done ``` -------------------------------- ### Redis Cluster Pub/Sub Example (JavaScript) Source: https://github.com/luin/ioredis This snippet demonstrates basic Pub/Sub functionality within a Redis Cluster using ioredis. It shows how to establish a cluster connection, subscribe to a channel, publish a message, and handle incoming messages. ```javascript const Redis = require("ioredis"); const nodes = [ /* nodes */ ]; const pub = new Redis.Cluster(nodes); const sub = new Redis.Cluster(nodes); sub.on("message", (channel, message) => { console.log(channel, message); }); sub.subscribe("news", () => { pub.publish("news", "highlights"); }); ``` -------------------------------- ### Redis Pub/Sub with ioredis (Subscriber) Source: https://github.com/luin/ioredis Example of a Redis subscriber script using ioredis. It subscribes to multiple channels and logs messages received on those channels. It also demonstrates handling messageBuffers. ```javascript const Redis = require("ioredis"); const redis = new Redis(); redis.subscribe("my-channel-1", "my-channel-2", (err, count) => { if (err) { console.error("Failed to subscribe: %s", err.message); } else { console.log( `Subscribed successfully! This client is currently subscribed to ${count} channels.` ); } }); redis.on("message", (channel, message) => { console.log(`Received ${message} from ${channel}`); }); redis.on("messageBuffer", (channel, message) => { // Both `channel` and `message` are buffers. console.log(channel, message); }); ``` -------------------------------- ### Configure Soketi to Use Redis Adapter Source: https://context7_llms This command configures Soketi to use Redis as the adapter for inter-node communication, essential for horizontal scaling. Ensure Redis is installed and accessible. ```bash ADAPTER_DRIVER=redis soketi start ``` -------------------------------- ### Enable Redis Adapter for Soketi Scaling Source: https://docs.soketi.app/advanced-usage/horizontal-scaling/redis-configuration This command demonstrates how to start the Soketi server using Redis as the adapter driver. This is crucial for enabling node-to-node communication in horizontally scaled environments like Kubernetes or PM2. Ensure Redis is running and accessible. ```bash SOKETI_ADAPTER_DRIVER=redis soketi start ``` -------------------------------- ### Getting Metrics from Amazon CloudWatch using JavaScript Source: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html This example demonstrates how to retrieve metric data from Amazon CloudWatch using the AWS SDK for JavaScript. It allows you to fetch statistics for a specific metric over a defined period, which is essential for performance monitoring and analysis. ```javascript const AWS = require('aws-sdk'); AWS.config.update({ region: 'us-east-1' }); const cloudwatch = new AWS.CloudWatch(); const params = { Namespace: 'AWS/EC2', MetricName: 'CPUUtilization', Dimensions: [ { Name: 'InstanceId', Value: 'i-0123456789abcdef0' // Replace with your instance ID } ], StartTime: new Date(Date.now() - 3600 * 1000), // Last hour EndTime: new Date(), Period: 60, // 1 minute Statistics: ['Average'] }; cloudwatch.getMetricStatistics(params, (err, data) => { if (err) { console.error('Error getting metrics:', err); } else { console.log('Metric data:', data.Datapoints); } }); ``` -------------------------------- ### Run ioredis Tests (Node.js) Source: https://github.com/luin/ioredis Instructions on how to run the tests for the ioredis library. It requires a Redis server running on `127.0.0.1:6379` and mentions that `FLUSH ALL` is executed after each test. It also suggests `ioredis-mock` as an alternative for testing environments where a Redis server cannot be started. ```bash npm test ``` -------------------------------- ### Configure Soketi with Environment Variables (Bash) Source: https://context7_llms Sets environment variables directly in the bash shell to configure Soketi. This example shows how to set the 'DEBUG' and 'ADAPTER_DRIVER' variables. These variables can also be defined in a '.env' file. ```bash DEBUG=1 ADAPTER_DRIVER=mysql soketi start ``` -------------------------------- ### JavaScript Client Event Triggering Example Source: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol A JavaScript code snippet demonstrating how to trigger a client event using the Pusher library. It shows subscribing to a private channel and preparing data to be sent with a client-originated event. ```javascript var pusher = new Pusher("APP_KEY"); var channel = pusher.subscribe("private-channel"); var data = { some: ``` -------------------------------- ### Kubernetes Service Deployment for Soketi Source: https://docs.soketi.app/network-watcher/installation This Kubernetes Service configuration defines how Soketi services are exposed. It specifies the selector to match Soketi pods and the port for WebSocket connections. The annotation `ws.soketi.app/accepts-new-connections: "yes"` is crucial for network traffic routing. ```yaml apiVersion: v1 kind: Service metadata: name: soketi-service spec: selector: app: soketi ws.soketi.app/accepts-new-connections: "yes" # required ports: - protocol: TCP port: 6001 targetPort: 6001 name: ws ``` -------------------------------- ### Set and Get Redis Keys with ioredis Source: https://github.com/luin/ioredis Demonstrates basic Redis key-value operations using ioredis. It covers setting a key-value pair, retrieving its value using both promises and callbacks, and setting keys with expiration. ```javascript const Redis = require("ioredis"); const redis = new Redis(); // Set a key-value pair redis.set("mykey", "value"); // Get a key's value using callback style redis.get("mykey", (err, result) => { if (err) { console.error(err); } else { console.log(result); // Prints "value" } }); // Get a key's value using promises redis.get("mykey").then((result) => { console.log(result); // Prints "value" }); // Set a key with an expiration time (10 seconds) redis.set("mykey", "hello", "EX", 10); ``` -------------------------------- ### Laravel .env Configuration for Pusher/Soketi Source: https://docs.soketi.app/getting-started/client-configuration/laravel-echo This snippet shows the typical environment variable setup in a Laravel application's .env file required for configuring PusherJS and consequently, Soketi. It defines keys, secrets, and host/port details that are then referenced by the application's client-side configuration. ```dotenv PUSHER_APP_KEY=app-key PUSHER_APP_ID=app-id PUSHER_APP_SECRET=app-secret PUSHER_HOST=127.0.0.1 PUSHER_PORT=6001 MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" MIX_PUSHER_HOST="${PUSHER_HOST}" MIX_PUSHER_PORT="${PUSHER_PORT}" ``` -------------------------------- ### Set Debug Mode via .env File Source: https://docs.soketi.app/getting-started/environment-variables This shows how to configure the Soketi server's debug mode using an .env file. By adding the SOKETI_DEBUG=1 line to your .env file, the server will start with debug mode enabled when run from the same directory. ```env # Within your .env file SOKETI_DEBUG=1 ``` -------------------------------- ### Configure Soketi with Environment Variables (File) Source: https://context7_llms Creates a '.env' file to store Soketi configuration variables. This method is useful for managing multiple configurations or for use in environments where direct command-line variable setting is not preferred. The 'soketi start' command will automatically load variables from this file. ```bash echo " DEBUG=1 ADAPTER_DRIVER=mysql " > .env ``` ```bash soketi start ``` -------------------------------- ### Set Debug Mode via Environment Variable (CLI) Source: https://docs.soketi.app/getting-started/environment-variables This snippet demonstrates how to enable debug mode for the Soketi server by setting the SOKETI_DEBUG environment variable directly in the command line when starting the server. This is useful for temporary debugging. ```bash SOKETI_DEBUG=1 soketi start ``` -------------------------------- ### Getting Model Broadcast Channel Name (PHP) Source: https://laravel.com/docs/8.x/broadcasting This example shows how to retrieve the broadcast channel name for a given model instance using the `broadcastChannel` method. It illustrates how Laravel generates channel names, such as 'App.Models.User.1' for a User model with ID 1. ```php $user->broadcastChannel() ``` -------------------------------- ### Configure Read-Write Splitting in ioredis Cluster Source: https://github.com/luin/ioredis Demonstrates how to configure ioredis to direct read queries to slave nodes in a Redis cluster, improving read performance. It shows the usage of the `scaleReads` option with 'slave' and provides an example of setting and getting a key, highlighting potential replication lag. ```javascript const Redis = require("ioredis"); const cluster = new Redis.Cluster( [ /* nodes */ ], { scaleReads: "slave", }); cluster.set("foo", "bar"); // This query will be sent to one of the masters. cluster.get("foo", (err, res) => { // This query will be sent to one of the slaves. }); ``` -------------------------------- ### Node.js User Authentication Endpoint Source: https://pusher.com/docs/channels/server_api/authenticating-users This Node.js example demonstrates how to set up an Express server to handle user authentication requests from Pusher clients. It uses the `pusher` library to generate authentication tokens. Ensure you have `pusher`, `express`, and `cors` installed. The endpoint expects a `socket_id` in the request body and returns an authentication response. ```javascript // First install the dependencies: // npm install pusher express cors const express = require("express"); const cors = require("cors"); const Pusher = require("pusher"); const pusher = new Pusher({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER", useTLS: true, }); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cors()); app.post("/pusher/user-auth", (req, res) => { const socketId = req.body.socket_id; // Replace this with code to retrieve the actual user id and info const user = { id: "some_id", user_info: { name: "John Smith", }, watchlist: ['another_id_1', 'another_id_2'] }; const authResponse = pusher.authenticateUser(socketId, user); res.send(authResponse); }); const port = process.env.PORT || 5000; app.listen(port); ``` -------------------------------- ### Redis Pub/Sub with ioredis Source: https://github.com/luin/ioredis Demonstrates how to set up a Redis client for publishing and subscribing to messages using ioredis. It shows basic subscription, message handling, and publishing at intervals. ```javascript const Redis = require("ioredis"); const sub = new Redis(); const pub = new Redis(); sub.subscribe(/* ... */); // From now, `sub` enters the subscriber mode. sub.on("message" /* ... */); setInterval(() => { // `pub` can be used to publish messages, or send other regular commands (e.g. `hgetall`) // because it's not in the subscriber mode. pub.publish(/* ... */); }, 1000); ``` -------------------------------- ### Running Soketi with Docker Source: https://context7_llms This command pulls and runs a Soketi Docker image, exposing the necessary ports for the application. It demonstrates a basic deployment for ARM-based devices and other architectures using pre-built images. ```bash docker run -p 6001:6001 -p 9601:9601 quay.io/soketi/soketi:0.34-16-debian ``` -------------------------------- ### Presence Channel Member Added Event Example Source: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol An example JSON payload for the 'pusher_internal:member_added' event. This demonstrates how a user's ID and their associated information (like name and Twitter handle) are sent when they join a presence channel. ```json { "event": "pusher_internal:member_added", "channel": "presence-example-channel", "data": "{ \"user_id\": \"11814b369700141b222a3f3791cec2d9\", \"user_info\": { \"name\": \"Phil Leggetter\", \"twitter\": \"@leggetter\", \"blogUrl\": \"http://blog.pusher.com\" } }" } ``` -------------------------------- ### Soketi Server Configuration via JSON File Source: https://context7_llms This example demonstrates configuring Soketi using a JSON file, which is supported from version 0.24 onwards. It allows for complex configurations, including defining multiple applications with their credentials and webhook settings. The `--config` flag points to the location of the configuration file. ```json { "debug": true, "port": 6002, "appManager.array.apps": [ { "id": "some-id", "key": "some-key", "secret": "some-secret", "webhooks": [ { "url": "https://...", "event_types": ["channel_occupied"] } ] } ] } ``` ```bash soketi start --config=/path/to/config.json ``` -------------------------------- ### Run PHPUnit Tests Source: https://github.com/soketi/network-watcher This command executes the project's test suite using PHPUnit. It points to the PHPUnit executable within the vendor directory, ensuring that the tests are run with the project's specific dependencies. ```bash vendor/bin/phpunit ``` -------------------------------- ### Redis Cluster Sharded Pub/Sub Example (TypeScript) Source: https://github.com/luin/ioredis This example illustrates how to use Sharded Pub/Sub with ioredis in TypeScript. It highlights the use of `shardedSubscribers: true`, subscribing to channels within the same slot using `ssubscribe`, and publishing messages with `spublish`. ```typescript import { Cluster } from 'ioredis'; const cluster: Cluster = new Cluster([{host: host, port: port}], {shardedSubscribers: true}); //Register the callback cluster.on("smessage", (channel, message) => { console.log(message); }); //Subscribe to the channels on the same slot cluster.ssubscribe("channel{my}:1", "channel{my}:2").then( ( count: number ) => { console.log(count); }).catch( (err) => { console.log(err); }); //Publish a message cluster.spublish("channel{my}:1", "This is a test message to my first channel.").then((value: number) => { console.log("Published a message to channel{my}:1"); }); ``` -------------------------------- ### Kubernetes Deployment with Soketi and Network Watcher Source: https://docs.soketi.app/network-watcher/installation This Kubernetes Deployment configuration sets up Soketi pods along with the Network Watcher container. It defines the Soketi image, ports, and environment variables for the Network Watcher, including memory thresholds and checking intervals. The `ws.soketi.app/accepts-new-connections: "yes"` label is applied to the pod template. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: soketi labels: app: soketi spec: replicas: 3 selector: matchLabels: app: soketi template: metadata: labels: app: soketi ws.soketi.app/accepts-new-connections: "yes" # optional spec: containers: - name: soketi image: soketi/soketi:0.17-16-alpine ports: - containerPort: 6001 - name: network-watcher image: quay.io/soketi/network-watcher:6 env: - name: KUBE_CONNECTION value: cluster - name: MEMORY_PERCENT value: "75" # if > 75% memory, reject new connections - name: CHECKING_INTERVAL value: "5" # every 5 seconds - name: POD_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name ``` -------------------------------- ### Handle Hashes with ioredis Source: https://github.com/luin/ioredis Shows how to perform operations on Redis Hash data structures, including setting multiple fields, getting a field's value, and getting all fields and values. Hashes are useful for storing structured data. ```javascript async function handleHashes() { try { // Set multiple fields in a hash await redis.hset('myhash', 'field1', 'value1', 'field2', 'value2'); console.log('Hash set successfully.'); // Get a single field from a hash const fieldValue1 = await redis.hget('myhash', 'field1'); console.log('Value of field1:', fieldValue1); // Get all fields and values from a hash const allFields = await redis.hgetall('myhash'); console.log('All fields and values:', allFields); } catch (err) { console.error('Error during hash operation:', err); } } handleHashes(); ``` -------------------------------- ### Scaling Soketi with PM2 Source: https://context7_llms This command utilizes the PM2-ready binary shipped with Soketi to scale the application across Node.js threads. This is a recommended approach for leveraging multi-core processors efficiently when running Soketi. ```bash soketi-pm2 start ``` -------------------------------- ### Run Soketi with Docker Source: https://context7_llms This command pulls and runs a Soketi Docker image, exposing the necessary ports for WebSocket communication and monitoring. It's a straightforward way to deploy Soketi without manual installation on the host system. Ensure the ports `6001` (for WebSocket) and `9601` (for dashboard/management) are correctly mapped. ```bash docker run -p 6001:6001 -p 9601:9601 quay.io/soketi/soketi:1.4-16-debian ``` -------------------------------- ### Stop Supervisor Daemon (Bash) Source: https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps This command stops the Supervisor parent daemon process. It's a fundamental operation for managing Supervisor services. ```bash service supervisor stop ``` -------------------------------- ### Soketi Webhook Filtering by Channel Name Source: https://docs.soketi.app/advanced-usage/app-webhooks Demonstrates how to filter webhooks to only include events from specific channels based on name patterns (starts with, ends with). ```json { "url": "string", "event_types": ["channel_occupied"], "filter": { "channel_name_starts_with": "beta-", "channel_name_ends_with": "-app" } } ``` -------------------------------- ### Redis Pub/Sub with ioredis (Publisher) Source: https://github.com/luin/ioredis Example of a Redis publisher script using ioredis. It periodically sends random JSON messages to different channels. ```javascript const Redis = require("ioredis"); const redis = new Redis(); setInterval(() => { const message = { foo: Math.random() }; const channel = `my-channel-${1 + Math.round(Math.random())}`; redis.publish(channel, JSON.stringify(message)); console.log("Published %s to %s", message, channel); }, 1000); ``` -------------------------------- ### Pusher Class Initialization Source: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol Shows the basic structure for initializing the main Pusher class, which is the entry point for establishing a connection to Pusher Channels. This class manages the connection object and the overall communication. ```javascript class Pusher {} // The Pusher class is the main class... ``` -------------------------------- ### Supervisor Configuration for Soketi Source: https://context7_llms This configuration file sets up Supervisor to manage the Soketi server. It ensures the server runs permanently, restarts on failure, and logs output. Key options include `autostart`, `autorestart`, `redirect_stderr`, and `minfds` for handling file descriptors. ```ini [program:soketi] process_name=%(program_name)s_%(process_num)02d command=soketi start autostart=true autorestart=true stopasgroup=true killasgroup=true user=ubuntu numprocs=1 redirect_stderr=true stdout_logfile=/var/log/soketi-supervisor.log stopwaitsecs=60 stopsignal=sigint minfds=10240 ``` -------------------------------- ### PHP: Encrypting Private Channels with Pusher SDK Source: https://context7_llms This PHP snippet demonstrates how to initialize the Pusher SDK with an `encryptionMasterKeyBase64` for encrypted private channels. Ensure the master key is securely generated and managed. ```php use Pusher\Pusher; $pusher = new Pusher('app-key', 'app-secret', 'app-id', [ // ... 'encryptionMasterKeyBase64' => '...', // // generate this with, e.g. 'openssl rand -base64 32' ]); ``` -------------------------------- ### Redis Sorted Sets with ioredis Source: https://github.com/luin/ioredis Illustrates how to use Redis sorted sets with ioredis. This example shows adding elements with scores and retrieving a range of elements along with their scores. ```javascript const Redis = require("ioredis"); const redis = new Redis(); redis.zadd("sortedSet", 1, "one", 2, "dos", 4, "quatro", 3, "three"); redis.zrange("sortedSet", 0, 2, "WITHSCORES").then((elements) => { // Returns ["one", "1", "dos", "2", "three", "3"] console.log(elements); }); ``` -------------------------------- ### Configure Laravel Broadcasting for Encryption Source: https://pusher.com/docs/channels/using_channels/encrypted-channels This example shows how to configure Laravel's broadcasting settings in `config/broadcasting.php` to use end-to-end encrypted channels. It involves setting `useTLS` to true and providing the `encryption_master_key_base64`. ```php // in config/broadcasting.php 'options' => [ 'useTLS' => true, 'encryption_master_key_base64' => 'YOUR_MASTER_KEY', // generate this with, e.g. 'openssl rand -base64 32' ], ``` -------------------------------- ### Configure Laravel Echo for Ably (JavaScript) Source: https://laravel.com/docs/8.x/broadcasting Sets up a Laravel Echo instance to connect to Ably, utilizing its Pusher compatibility mode. This requires installing pusher-js and configuring Echo with the Ably public key. ```javascript import Echo from 'laravel-echo'; window.Pusher = require('pusher-js'); window.Echo = new Echo({ broadcaster: 'pusher', key: process.env.MIX_ABLY_PUBLIC_KEY ``` -------------------------------- ### Redis Pipelining with ioredis Source: https://github.com/luin/ioredis Illustrates efficient batching of Redis commands using ioredis pipelines. It covers creating a pipeline, queuing commands, executing them, and handling results with callbacks or Promises. ```javascript const pipeline = redis.pipeline(); pipeline.set("foo", "bar"); pipeline.del("cc"); pipeline.exec((err, results) => { // `err` is always null, and `results` is an array of responses // corresponding to the sequence of queued commands. // Each response follows the format `[err, result]`. }); ``` ```javascript const promise = redis.pipeline().set("foo", "bar").get("foo").exec(); promise.then((result) => { // result === [[null, 'OK'], [null, 'bar']] }); ``` ```javascript redis .pipeline() .set("foo", "bar") .get("foo", (err, result) => { // result === 'bar' }) .exec((err, result) => { // result[1][1] === 'bar' }); ``` ```javascript redis .pipeline([ ["set", "foo", "bar"], ["get", "foo"], ]) .exec(() => { /* ... */ }); ``` -------------------------------- ### Redis Streams Consumer with ioredis Source: https://github.com/luin/ioredis Provides an example of how to consume messages from a Redis stream using ioredis. It includes a function to process individual messages and a recursive listener for continuous consumption. ```javascript const Redis = require("ioredis"); const redis = new Redis(); const processMessage = (message) => { console.log("Id: %s. Data: %O", message[0], message[1]); }; async function listenForMessage(lastId = "$") { // `results` is an array, each element of which corresponds to a key. // Because we only listen to one key (mystream) here, `results` only contains // a single element. See more: https://redis.io/commands/xread#return-value const results = await redis.xread("BLOCK", 0, "STREAMS", "mystream", lastId); const [key, messages] = results[0]; // `key` equals to "mystream" messages.forEach(processMessage); // Pass the last id of the results to the next round. await listenForMessage(messages[messages.length - 1][0]); } listenForMessage(); ``` -------------------------------- ### Customize Broadcastable Model Event Creation Source: https://laravel.com/docs/8.x/broadcasting Provides an example of customizing the creation of the underlying model broadcasting event by defining a `newBroadcastableEvent` method. This allows for modifications like preventing broadcasting to the current user. ```php use Illuminate\Database\Eloquent\BroadcastableModelEventOccurred; /** * Create a new broadcastable model event for the model. * * @param string $event * @return \Illuminate\Database\Eloquent\BroadcastableModelEventOccurred */ protected function newBroadcastableEvent($event) { return (new BroadcastableModelEventOccurred( $this, $event ))->dontBroadcastToCurrentUser(); } ``` -------------------------------- ### Soketi HTTP Webhook Configuration Example Source: https://context7_llms Defines the structure for configuring Soketi HTTP webhooks, including the destination URL, event types to trigger the webhook, and optional filtering and custom headers. Webhooks can be triggered by various events like client events, channel occupations, and member changes. ```json { "url": "string", "event_types": ["string", ...] } ``` ```json { "url": "string", "event_types": ["channel_occupied"], "filter": { "channel_name_starts_with": "beta-", "channel_name_ends_with": "-app" } } ``` ```json { "url": "string", "event_types": ["channel_occupied"], "headers": { "X-Custom-Header": "Custom Header", "X-Version": "Custom Header" } } ```