### Install piectl globally
Source: https://piehost.com/docs/3.0/piesocket-onprem
Install the PieSocket CLI tool globally using npm.
```bash
npm i -g piectl
```
--------------------------------
### Install websockets package with pip
Source: https://piehost.com/docs/3.0/python-websocket
Install the websockets package using pip. This is the required setup step before building the server and client.
```bash
pip install websockets
```
--------------------------------
### Start PieSocket server
Source: https://piehost.com/docs/3.0/piesocket-onprem
Start the self-hosted PieSocket server. The dashboard will be available at http://localhost:4000 on first run.
```bash
pie socket serve
```
--------------------------------
### Install pusher/pusher-php-server
Source: https://piehost.com/docs/3.0/piesocket-laravel
Install the Pusher PHP server library required for Laravel broadcasting with PieSocket.
```bash
composer require pusher/pusher-php-server
```
--------------------------------
### PieCache Node.js ioredis example
Source: https://piehost.com/docs/3.0/overview
Node.js example using ioredis to connect to PieCache and perform a set with expiration and a get.
```javascript
const Redis = require('ioredis');
const client = new Redis('rediss://:YOUR_PASSWORD@your-cache.piehost.com:6380');
await client.set('key', 'value', 'EX', 3600);
const val = await client.get('key');
```
--------------------------------
### Set Pro license key and start Pie Socket server
Source: https://piehost.com/docs/3.0/piesocket-onprem
Sets the PRO_LICENSE_KEY environment variable and runs 'pie socket serve' to start the server with Pro features enabled.
```bash
PRO_LICENSE_KEY=your-key-here pie socket serve
```
--------------------------------
### Laravel deployment settings for PieApp
Source: https://piehost.com/docs/3.0/overview
Example settings for deploying a Laravel app on PieApp. Use these values in the dashboard's build and start command fields, and set the Node and PHP versions accordingly.
```text
CopyBuild command: composer install --no-dev && php artisan migrate --force
Start command: php artisan serve --host=0.0.0.0 --port=8080
Node version: 20
PHP version: 8.3
```
--------------------------------
### Install PieSocketJS via NPM
Source: https://piehost.com/docs/3.0/portals
Install the PieSocketJS library using npm. This is the first step to include the library in your application.
```bash
npm install piesocket-js
```
--------------------------------
### Install laravel-echo and pusher-js
Source: https://piehost.com/docs/3.0/piesocket-laravel
Install Laravel Echo and pusher-js as dev dependencies for the frontend.
```bash
npm install --save-dev laravel-echo pusher-js
```
--------------------------------
### Install PieSocketJS with Yarn or npm
Source: https://piehost.com/docs/3.0/javascript-websocket
Install the PieSocket JavaScript SDK version 5 using either Yarn or npm. Choose the command that matches your package manager.
```bash
yarn add piesocket-js@5
```
```bash
npm i piesocket-js@5
```
--------------------------------
### Create basic HTML structure for piesocket.html
Source: https://piehost.com/docs/3.0/websocket-example
Start with a basic HTML page structure. Save this as piesocket.html.
```html
PieSocket Tester
```
--------------------------------
### Start master node in cluster mode
Source: https://piehost.com/docs/3.0/piesocket-onprem
Starts the master node for horizontal scaling. Requires a valid Pro license, Redis with PIE_PUBSUB_DRIVER=redis, and PIE_REDIS_URL pointing to a shared Redis instance.
```bash
PRO_LICENSE_KEY=your-key PIE_PUBSUB_DRIVER=redis PIE_REDIS_URL=redis://your-redis pie socket serve
```
--------------------------------
### Initialize PieSocket with options
Source: https://piehost.com/docs/3.0/piesocket-flutter
Create PieSocketOptions with your cluster ID and API key, then instantiate the PieSocket client. Get your API key and Cluster ID from the PieSocket account.
```dart
PieSocketOptions options = PieSocketOptions();
options.setClusterId("demo");
options.setApiKey("VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV");
PieSocket piesocket = PieSocket(options);
```
--------------------------------
### PieMongo Node.js mongoose example
Source: https://piehost.com/docs/3.0/overview
Node.js example using mongoose to connect to PieMongo. The connection URI is taken from the MONGO_URI environment variable.
```javascript
const mongoose = require('mongoose');
await mongoose.connect(process.env.MONGO_URI);
```
--------------------------------
### Enable Pusher-compatible mode (ENABLE_PUSHER)
Source: https://piehost.com/docs/3.0/piesocket-onprem
Starts the server in Pusher-compatible mode. Set ENABLE_PUSHER=true to enable the Pusher-compatible endpoint; the server then accepts official Pusher client SDKs without code changes.
```bash
ENABLE_PUSHER=true pie socket serve
```
--------------------------------
### Enable Presence with pieSocketOptions.setPresence
Source: https://piehost.com/docs/3.0/piesocket-android
Enable Presence features for a room to see who is in it, get system:member_joined to fire, and track when people leave.
```java
CopypieSocketOptions.setPresence(true);
```
--------------------------------
### Install PieSocketJS and react-native-get-random-values
Source: https://piehost.com/docs/3.0/piesocket-react-native
Install the required dependencies for using PieSocketJS in a React Native project. The react-native-get-random-values package is needed as a polyfill for the global crypto.getRandomValues.
```bash
npm install piesocket-js
npm install react-native-get-random-values
```
--------------------------------
### Example: MainActivity with PieSocket channel
Source: https://piehost.com/docs/3.0/piesocket-android
Sample Activity that logs "Channel connected" to logcat when the channel is ready. Channels should generally be initialised into a foreground/background service.
```java
package com.piesocket.android;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.piesocket.android.databinding.ActivityMainBinding;
import com.piesocket.channels.Channel;
import com.piesocket.channels.PieSocket;
import com.piesocket.channels.misc.PieSocketEvent;
import com.piesocket.channels.misc.PieSocketEventListener;
import com.piesocket.channels.misc.PieSocketOptions;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private PieSocket piesocket;
private Channel channel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
PieSocketOptions pieSocketOptions = new PieSocketOptions();
pieSocketOptions.setClusterId("demo");
pieSocketOptions.setApiKey("VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV");
piesocket = new PieSocket(pieSocketOptions);
channel = piesocket.join("chat-room");
channel.listen("system:connected", new PieSocketEventListener() {
@Override
public void handleEvent(PieSocketEvent event) {
Log.d("PIESOCKET-SDK", "Channel connected");
PieSocketEvent clientEvent = new PieSocketEvent("testevent");
clientEvent.setData("Hello!");
channel.publish(clientEvent);
}
});
channel.listen("testevent", new PieSocketEventListener() {
@Override
public void handleEvent(PieSocketEvent event) {
Log.d("PIESOCKET-SDK", "testevent was fired");
}
});
}
}
```
--------------------------------
### Publish with PieSocket NodeJS SDK
Source: https://piehost.com/docs/3.0/nodejs-websocket
Install the PieSocket NodeJS SDK, initialize the PieSocket class with your cluster ID, API key, and secret, then publish messages to a WebSocket room using the publish method.
```bash
npm i piesocket-nodejs
```
```javascript
const PieSocket = require("piesocket-nodejs");
var piesocket = new PieSocket({
clusterId: 'YOUR_CLUSTER_ID',
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_API_SECRET'
});
```
```javascript
piesocket.publish(roomId, data);
```
--------------------------------
### Start worker node in cluster mode
Source: https://piehost.com/docs/3.0/piesocket-onprem
Starts a worker node that connects to the master at master-host:4000. Workers self-register, send heartbeats every 30 seconds, and re-register if the master restarts.
```bash
PRO_LICENSE_KEY=your-key PIE_PUBSUB_DRIVER=redis PIE_REDIS_URL=redis://your-redis pie socket serve --cluster master-host:4000
```
--------------------------------
### GET https://www.piesocket.com/api/domains
Source: https://piehost.com/docs/3.0/rest-api
Returns a list of all allowed domains for an API key.
```APIDOC
## [GET] https://www.piesocket.com/api/domains
### Description
Returns a list of all allowed domains for an API key.
### Method
GET
### Endpoint
https://www.piesocket.com/api/domains
### Parameters
This API endpoint accepts no parameters.
### Response
#### Success Response (200)
- **domains** (array) - List of allowed domains for the API key.
#### Response Example
{
"domains": ["example.com", "example.org"]
}
```
--------------------------------
### Server-side Pusher configuration with PieSocket
Source: https://piehost.com/docs/3.0/pusher-to-piesocket
Replace app_id, app_key, and app_secret with PieSocket's credentials and set the host to your PieSocket cluster. The example shows triggering an event.
```php
$app_id = 'PIESOCKET_API_ID';
$app_key = 'PIESOCKET_API_KEY';
$app_secret = 'PIESOCKET_API_SECRET';
$app_cluster = 'piesocket';
$pusher = new PusherPusher(
$app_key,
$app_secret,
$app_id,
[
'host' => '[PIESOCKET_CLUSER_ID].piesocket.com',
'cluster' => $app_cluster
]
);
$pusher->trigger('my-channel', 'my-event', 'hello world'));
```
--------------------------------
### Add headers to authEndpoint request
Source: https://piehost.com/docs/3.0/piesocket-swift
Optionally add headers to the authEndpoint request. The example sets Accept and Content-type headers to application/json.
```swift
var headers : [String: String] = [String: String]()
headers["Accept"] = "application/json"
headers["Content-type"] = "application/json"
options.setAuthHeaders(authHeaders: headers)
```
--------------------------------
### Add Vite directive to welcome.blade.php
Source: https://piehost.com/docs/3.0/piesocket-laravel
Add this line inside the section of welcome.blade.php if the frontend setup does not work. Ensure npm run dev is running.
```blade
@vite('resources/js/app.js', 'vendor/courier/build')
```
--------------------------------
### GET https://www.piesocket.com/api/connections
Source: https://piehost.com/docs/3.0/rest-api
Returns a list of all active Channel rooms and their connection count for the authenticated API key.
```APIDOC
## [GET] https://www.piesocket.com/api/connections
### Description
Returns a list of all active Channel rooms and their connection count for the authenticated API key.
### Method
GET
### Endpoint
https://www.piesocket.com/api/connections
### Parameters
This API endpoint accepts no parameters.
### Response
#### Success Response (200)
- **rooms** (array) - List of active Channel rooms with their connection counts.
#### Response Example
{
"rooms": [
{
"room": "room1",
"connections": 5
}
]
}
```
--------------------------------
### Add headers to the authEndpoint request
Source: https://piehost.com/docs/3.0/piesocket-flutter
Optionally add headers to the authEndpoint request. The example sets Content-type and Accept headers.
```dart
Copyvar headers = {"Content-type": "application/json", "Accept": "application/json"};
options.setAuthHeaders(headers);
```
--------------------------------
### List all room members with channel.getAllMembers
Source: https://piehost.com/docs/3.0/piesocket-android
Get a JSONArray containing all members of the room. Requires Presence features enabled.
```java
CopyJSONArray members = channel.getAllMembers()
```
--------------------------------
### Complete Android manifest with permission and cleartext traffic
Source: https://piehost.com/docs/3.0/piesocket-android
Example of the application tag with the INTERNET permission and usesCleartextTraffic attribute, as described in the documentation.
```xml
```
--------------------------------
### GET https://www.piesocket.com/api/members
Source: https://piehost.com/docs/3.0/rest-api
Returns a list of channels and presence members inside them - please note, only members with presence=1 will be listed.
```APIDOC
## [GET] https://www.piesocket.com/api/members
### Description
Returns a list of channels and presence members inside them - please note, only members with presence=1 will be listed.
### Method
GET
### Endpoint
https://www.piesocket.com/api/members
### Parameters
This API endpoint accepts no parameters.
### Response
#### Success Response (200)
- **channels** (array) - List of channels with their presence members.
#### Response Example
{
"channels": [
{
"channel": "channel1",
"members": ["user1", "user2"]
}
]
}
```
--------------------------------
### Include PieSocketJS via CDN
Source: https://piehost.com/docs/3.0/portals
Include the PieSocketJS library in your HTML page using a CDN script tag. This is an alternative to the npm installation.
```html
```
--------------------------------
### Publish an event from the client
Source: https://piehost.com/docs/3.0/piesocket-swift
Use the publish method to send an event from the client. Requires enabling client-to-client communication in the PieSocket cluster (enabled by default in new clusters). The example listens for the system:connected event and publishes a new_message event.
```swift
channel.listen(eventName: "system:connected", callback: {event in
//Channel is connected
//Construct an event
let newMessage = PieSocketEvent(event: "new_message")
newMessage.setData(data: "Hello world!")
//Publish the event
channel.publish(event: newMessage)
})
```
--------------------------------
### Reverse Proxy Setup (nginx)
Source: https://piehost.com/docs/3.0/piesocket-onprem
Use this nginx configuration to serve the PieSocket dashboard and WebSocket server from a single domain. It proxies the dashboard on port 4000 and the WebSocket endpoint on port 4001, with the required upgrade headers for WebSocket connections.
```nginx
server {
listen 80;
server_name your-domain.com;
# Dashboard
location / {
proxy_pass http://localhost:4000;
}
# WebSocket
location /ws/ {
proxy_pass http://localhost:4001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
}
}
```
--------------------------------
### Publish an event from the client
Source: https://piehost.com/docs/3.0/piesocket-flutter
Use the publish method to send an event from the client. Requires enabling client-to-client communication in the PieSocket cluster (enabled by default in new clusters). The example listens for the system:connected event, creates a new event with data, and publishes it.
```dart
Copychannel.listen("system:connected", (PieSocketEvent event) {
//Channel is connected
//Create an event
PieSocketEvent newMessage = PieSocketEvent("new_message");
newMessage.setData("Hello World!");
//Publish event
room.publish(newMessage);
});
```
--------------------------------
### Listen to a channel event with PieSocketEventListener
Source: https://piehost.com/docs/3.0/piesocket-android
Attach a listener to a channel event. Multiple listeners can be added for the same event; all are called when the event fires. The example listens for the "new-message" event and logs the data.
```java
channel.listen("new-message", new PieSocketEventListener() {
@Override
public void handleEvent(PieSocketEvent event) {
Log.d("PIESOCKET-SDK", "New message received: "+ event.getData());
}
});
```
--------------------------------
### WebSocket API connection URL (wss://CLUSTER_ID.piesocket.com/v3/ROOM_ID?api_key=API_KEY¬ify_self=1)
Source: https://piehost.com/docs/3.0/piesocket-3rd-party-clients
WebSocket URL template for connecting to a PieSocket server. Replace CLUSTER_ID, ROOM_ID, and API_KEY with actual values. The API key can be generated from PieSocket cloud dashboard or self-hosted dashboard. The notify_self parameter is included as part of the example URL.
```text
wss://CLUSTER_ID.piesocket.com/v3/ROOM_ID?api_key=API_KEY¬ify_self=1
```
--------------------------------
### Get current member
Source: https://piehost.com/docs/3.0/javascript-websocket
Gets information about the current member. Requires presence to be enabled.
```javascript
var member = channel.getCurrentMember();
```
--------------------------------
### Upgrading PieSocket Server
Source: https://piehost.com/docs/3.0/piesocket-onprem
Run this command to upgrade PieSocket Server. Database migrations run automatically on startup, so no manual steps are required.
```bash
pie socket update
```
--------------------------------
### Get current member with channel.getCurrentMember
Source: https://piehost.com/docs/3.0/piesocket-android
Get information about the current member. Requires Presence features enabled.
```java
CopyJSONObject me = channel.getCurrentMember()
```
--------------------------------
### Initialize PieSocket with API Key and Cluster ID
Source: https://piehost.com/docs/3.0/piesocket-swift
Create PieSocketOptions, set cluster ID and API key, then instantiate PieSocket. Replace the placeholder values with your own credentials.
```swift
let options: PieSocketOptions = PieSocketOptions();
options.setClusterId(clusterId: "demo");
options.setApiKey(apiKey: "VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV");
let piesocket: PieSocket = PieSocket(pieSocketOptions: options);
```
--------------------------------
### Connect to PieDB MySQL with mysql CLI
Source: https://piehost.com/docs/3.0/overview
Connects to a PieDB MySQL instance using the host, port, user, and database name from the dashboard. Replace the placeholders with your actual connection details.
```bash
mysql -h YOUR_HOST -P 3306 -u YOUR_USER -p YOUR_DATABASE
```
--------------------------------
### Import PieSocket and polyfill in index.js
Source: https://piehost.com/docs/3.0/piesocket-react-native
Add these imports to your index.js file to set up the polyfill and import PieSocket. This must be done before using PieSocket Channels.
```javascript
import 'react-native-get-random-values'
import PieSocket from 'piesocket-js';
```
--------------------------------
### List all room members
Source: https://piehost.com/docs/3.0/javascript-websocket
Gets a list of all members in the room. Requires presence to be enabled.
```javascript
var members = channel.members;
```
--------------------------------
### Python WebSocket Client with websockets.connect
Source: https://piehost.com/docs/3.0/python-websocket
These Python snippets build a WebSocket client using the websockets library. The first imports asyncio and websockets, the second defines an async test coroutine, the third connects to a PieSocket demo channel using websockets.connect, the fourth sends a "hello" message, and the final full code combines all steps and runs the coroutine with asyncio.get_event_loop().run_until_complete. Replace YOUR_API_KEY with a valid PieSocket API key; the expected output is "hello".
```python
import asyncio
import websockets
```
```python
async def test():
```
```python
async def test():
async with websockets.connect('wss://demo.piesocket.com/v3/channel_1?api_key=YOUR_API_KEY') as websocket:
```
```python
await websocket.send("hello")
```
```python
import asyncio
import websockets
async def test():
async with websockets.connect('wss://demo.piesocket.com/v3/channel_1?api_key=YOUR_API_KEY') as websocket:
await websocket.send("hello")
response = await websocket.recv()
print(response)
asyncio.get_event_loop().run_until_complete(test())
```
--------------------------------
### Get current member information
Source: https://piehost.com/docs/3.0/piesocket-swift
Retrieve information about the current member using getCurrentMember().
```swift
let member: AnyObject? = channel.getCurrentMember()
```
--------------------------------
### GET https://www.piesocket.com/api/connections/sum
Source: https://piehost.com/docs/3.0/rest-api
Returns a count of total active connections for the authenticated API key.
```APIDOC
## [GET] https://www.piesocket.com/api/connections/sum
### Description
Returns a count of total active connections for the authenticated API key.
### Method
GET
### Endpoint
https://www.piesocket.com/api/connections/sum
### Parameters
This API endpoint accepts no parameters.
### Response
#### Success Response (200)
- **total** (integer) - Total number of active connections.
#### Response Example
{
"total": 100
}
```
--------------------------------
### Create WebSocket server with websockets and asyncio
Source: https://piehost.com/docs/3.0/python-websocket
Creates a WebSocket server that listens on localhost:8000. The handler receives a message, constructs a reply with the received data, and sends it back. Uses asyncio to run the server indefinitely.
```python
import asyncio
import websockets
# create handler for each connection
async def handler(websocket, path):
data = await websocket.recv()
reply = f"Data recieved as: {data}!"
await websocket.send(reply)
start_server = websockets.serve(handler, "localhost", 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
```
--------------------------------
### Get current member information
Source: https://piehost.com/docs/3.0/piesocket-flutter
Retrieve information about the current member using the getCurrentMember method.
```dart
Copyvar member = room.getCurrentMember();
```
--------------------------------
### Initialize PieSocket with API key and cluster ID
Source: https://piehost.com/docs/3.0/piesocket-android
Initialize the PieSocket client by creating a PieSocketOptions object, setting the cluster ID and API key, then passing it to the PieSocket constructor. Required before subscribing to channels.
```java
PieSocketOptions options = new PieSocketOptions();
options.setClusterId("demo");
options.setApiKey("VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV");
PieSocket piesocket = new PieSocket(options);
```
--------------------------------
### GET https://www.piesocket.com/api/logs
Source: https://piehost.com/docs/3.0/rest-api
Returns a list of most recent 500 messages from a PieSocket cluster, for the specified API key.
```APIDOC
## [GET] https://www.piesocket.com/api/logs
### Description
Returns a list of most recent 500 messages from a PieSocket cluster, for the specified API key.
### Method
GET
### Endpoint
https://www.piesocket.com/api/logs
### Parameters
This API endpoint accepts no parameters.
### Response
#### Success Response (200)
- **logs** (array) - List of recent messages.
#### Response Example
{
"logs": [
{
"message": "Hello",
"timestamp": "2023-01-01T00:00:00Z"
}
]
}
```
--------------------------------
### Set ports individually via environment variables
Source: https://piehost.com/docs/3.0/piesocket-onprem
Set the WebSocket, Publisher, and Dashboard ports individually using environment variables.
```bash
SOCKETPORT=4001 PUBLISHERPORT=4002 PORT=4000 pie socket serve
```
--------------------------------
### Build a chatroom with PieSocket
Source: https://piehost.com/docs/3.0/piesocket-js
Complete HTML file for a serverless chatroom using PieSocket. Replace YOUR_API_KEY with a key from the Channels dashboard, then open the file in multiple browser tabs to chat with yourself, or host it on a web server to chat with friends in real time.
```html
PieSocket Tester
```
--------------------------------
### Initialize PieSocket when using script tag
Source: https://piehost.com/docs/3.0/javascript-websocket
Use this syntax when loading PieSocket via a script tag, because the global variable is PieSocket.default. Pass the same configuration object as in the standard initialization.
```javascript
var pieSocket = new PieSocket.default({...});
```
--------------------------------
### Initialize PieSocket SDK with self-hosted server
Source: https://piehost.com/docs/3.0/piesocket-onprem
Initialize the PieSocket JavaScript SDK to connect to a self-hosted server using clusterDomain and ssl options.
```javascript
var pieSocket = new PieSocket({
clusterDomain: "localhost:4000",
ssl:false,
apiKey: "testkey",
notifySelf: true
});
```
--------------------------------
### Subscribe to a video room with local video
Source: https://piehost.com/docs/3.0/portals
Subscribe to a channel room with video enabled. The onLocalVideo callback sets up the local video element with the camera stream.
```javascript
piesocket.subscribe("video-chat-room", {
video: true,
onLocalVideo: (stream, video) => {
var localVideo = document.getElementById("self-video");
localVideo.muted = true;
localVideo.autoplay = true;
localVideo.srcObject = stream;
}
});
```
--------------------------------
### Pusher-Compatible Mode
Source: https://piehost.com/docs/3.0/piesocket-onprem
Configure and use the server as a drop-in replacement for Pusher, including supported features and advanced tuning variables.
```APIDOC
## [Configuration] Pusher-Compatible Mode
### Description
The server can act as a drop-in replacement for Pusher, allowing use of official Pusher client SDKs without code changes. Presence channels, cache channels, client events, and the Pusher Events REST API (POST /apps/:id/events) are supported.
### Enable Pusher Mode
- Set environment variable `ENABLE_PUSHER=true` and run `pie socket serve`.
### Client SDK Configuration
Configure your Pusher SDK to point to the self-hosted server.
### Example (JavaScript SDK)
```
const pusher = new Pusher('your-app-key', {
wsHost: 'your-server-host',
wsPort: 4001,
forceTLS: false,
cluster: 'mt1', // required by SDK but ignored by the server
});
```
### Configuration Variables (Optional)
- **PUSHER_CACHE_TTL_SECONDS** (integer) - Default: 1800 - How long data published to a cache channel (cache-*) is retained.
- **PIE_PRESENCE_HEARTBEAT_MS** (integer) - Default: 20000 - Presence channel heartbeat interval, in ms.
- **PIE_PRESENCE_STALE_MS** (integer) - Default: 60000 - How long before an unresponsive presence member is considered gone, in ms.
```
--------------------------------
### Command Messages
Source: https://piehost.com/docs/3.0/websocket-api
Reserved string messages starting with `cmd_` that send queries to the WebSocket server. Must use `notify_self=1` to receive responses.
```APIDOC
## Command Messages
### Description
Command messages are reserved string messages that start with `cmd_` and are used to send queries to the WebSocket server. To receive responses, `notify_self` must be enabled.
### cmd_status
#### Description
Responds with the number of connected clients to the room.
#### Example
Sending `"cmd_status"` to a Channels room results in the following response:
```json
{"system":{"connection_count":1}}
```
### cmd_ping
#### Description
Responds with `"pong"`.
#### Example
Sending `"cmd_ping"` to a Channels room results in the following response:
```json
{"system":"pong"}
```
```
--------------------------------
### Client-side Pusher initialization with PieSocket
Source: https://piehost.com/docs/3.0/pusher-to-piesocket
Replace the Pusher app key with your PieSocket API key and add wsHost and enabledTransports options. No other code changes are required.
```javascript
var pusher = new Pusher("[PIESOCKET_API_KEY]", {
wsHost: '[PIESOCKET_CLUSER_ID].piesocket.com',
enabledTransports: ['ws', 'wss'],
cluster: "piesocket"
});
var channel = pusher.subscribe("my-channel");
```
--------------------------------
### Health check endpoint (GET /api/health)
Source: https://piehost.com/docs/3.0/piesocket-onprem
Health check endpoint returning a JSON status object. The response shown is the expected output when the server is healthy.
```http
GET http://localhost:4000/api/health
→ { "status": "ok" }
```
--------------------------------
### Initialize PieSocket with clusterId and apiKey
Source: https://piehost.com/docs/3.0/javascript-websocket
Initialize a PieSocket client by providing your cluster ID and API key. The notifySelf option controls whether the client receives its own messages. Replace the demo values with your own credentials from your PieSocket account.
```javascript
var pieSocket = new PieSocket({
clusterId: "demo",
apiKey: "VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV",
notifySelf: true
});
```
--------------------------------
### WebSocket Client HTML Test Page
Source: https://piehost.com/docs/3.0/python-websocket
Create a client.html file with this HTML/JavaScript code to test a WebSocket server running locally on ws://localhost:8000. The page includes a button that sends an "Initialize" message, and the console logs incoming messages. Save and open the file in a browser to see the connection established.
```html
WebSocker Client
```
--------------------------------
### Initialize PieSocket
Source: https://piehost.com/docs/3.0/portals
Initialize the PieSocket client with your cluster ID, API key, and user ID. Set consoleLogs, notifySelf, and presence options as needed.
```javascript
var piesocket = new PieSocket({
clusterId: 'YOUR_CLUSTER_ID',
apiKey: 'YOUR_API_KEY',
consoleLogs: true,
notifySelf: true,
presence: true,
userId: "John"
});
```
--------------------------------
### Laravel S3 filesystem config for PieBucket
Source: https://piehost.com/docs/3.0/overview
Configure Laravel's filesystem to use PieBucket as the S3 driver. Set the endpoint and URL to https://storage.piehost.com and use environment variables for the key, secret, and bucket.
```php
's3' => [
'driver' => 's3',
'key' => env('PIEBUCKET_KEY'),
'secret' => env('PIEBUCKET_SECRET'),
'region' => 'us-east-1',
'bucket' => env('PIEBUCKET_BUCKET'),
'url' => 'https://storage.piehost.com',
'endpoint' => 'https://storage.piehost.com',
],
```
--------------------------------
### Add npm global bin to PATH (Windows PowerShell)
Source: https://piehost.com/docs/3.0/piesocket-onprem
Fix 'command not found' by adding the npm global bin directory to PATH in PowerShell.
```powershell
$env:PATH += ";$(npm root -g).bin"
```
--------------------------------
### Remove an event listener with removeListener()
Source: https://piehost.com/docs/3.0/piesocket-android
Remove a specific event listener by passing the same PieSocketEventListener instance that was used to listen. The example removes the listener for the "new-message" event.
```java
channel.removeListener("new-message", new PieSocketEventListener() {
@Override
public void handleEvent(PieSocketEvent event) {
Log.d("PIESOCKET-SDK", "New message received: "+ event.getData());
}
});
```
--------------------------------
### Prometheus metrics endpoint (GET /v3/metrics)
Source: https://piehost.com/docs/3.0/piesocket-onprem
Prometheus metrics endpoint returning metrics in Prometheus text format. In cluster mode, this endpoint automatically aggregates metrics from all live worker nodes.
```http
GET http://localhost:4001/v3/metrics
```
--------------------------------
### Full HTML chat web-app with PieSocket WebSocket
Source: https://piehost.com/docs/3.0/websocket-example
Full working HTML file for a real-time chat web-app using PieSocket WebSocket. Save it as an HTML file, open it in multiple tabs, and send messages to see them appear in all tabs. Uses the demo WebSocket URL wss://demo.piesocket.com/v3/1?api_key=oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm¬ify_self and handles new_message and new_joining events.
```html
Test PieSocket
```
--------------------------------
### Handle participants with onParticipantJoined and onParticipantLeft
Source: https://piehost.com/docs/3.0/portals
Subscribe to a room with both video and audio, and handle remote participants by creating and removing video elements. The onParticipantJoined callback appends a video element to a container with id 'video-room', and onParticipantLeft removes it.
```javascript
piesocket.subscribe("video-chat-room", {
video: true,
audio: true,
onLocalVideo: (stream, video) => {
//Creates local video
var localVideo = document.getElementById("self-video");
localVideo.muted = true;
localVideo.autoplay = true;
localVideo.srcObject = stream;
},
onParticipantJoined: (uuid, stream) => {
//Creates remote video
var videoHolder = document.createElement("video");
videoHolder.setAttribute("autoplay", true);
videoHolder.srcObject = stream;
videoHolder.id = uuid;
document.getElementById("video-room").append(videoHolder);
},
onParticipantLeft: (uuid) => {
//Removes video element
document.getElementById(uuid).remove();
}
})
```
--------------------------------
### Run dispatch:neworder artisan command
Source: https://piehost.com/docs/3.0/piesocket-laravel
Execute the artisan command to dispatch the NewOrder event. This will trigger the event and should result in an alert and console log in the browser.
```bash
php artisan dispatch:neworder
```
--------------------------------
### Scrape local node metrics (GET /v3/metrics?local=1)
Source: https://piehost.com/docs/3.0/piesocket-onprem
Scrapes only the local node's metrics, useful when Prometheus scrapes workers individually. The local=1 query parameter limits the response to the current node.
```http
GET http://localhost:4001/v3/metrics?local=1
```
--------------------------------
### Stand-alone usage: create Channel with wss URL
Source: https://piehost.com/docs/3.0/piesocket-android
Use this to connect to third-party WebSocket servers. Skipping the configuration part and creating a Channel instance directly means you miss out on features like Private Channels, Presence Channels, and Multiple Rooms.
```java
Channel channel = new Channel("wss://example.com", true);
```
--------------------------------
### Send an event payload to a WebSocket Channel Room
Source: https://piehost.com/docs/3.0/go-websocket
Use this JSON payload to send an event instead of a plain message. Replace the message field in the Go example with this payload to trigger an event named 'new-message' with data 'Hello'.
```json
{"event":"new-message","data":"Hello"}
```
--------------------------------
### Listen to a channel event with channel.listen
Source: https://piehost.com/docs/3.0/javascript-websocket
Attach an event listener to a channel using the listen method. The callback receives the event data and metadata. You can also listen to system events like system:member_joined and system:member_left.
```javascript
pieSocket.subscribe("chat-room").then((channel)=>{
console.log("Channel is ready");
channel.listen("new_message", (data, meta)=>{
console.log("New message: ", data);
});
});
```
--------------------------------
### Create DispatchOrder artisan command
Source: https://piehost.com/docs/3.0/piesocket-laravel
Run this artisan command to generate a new console command class named DispatchOrder. The class will be created in app/Console/Commands.
```bash
php artisan make:command DispatchOrder
```
--------------------------------
### Stand-alone Usage with Channel(webSocketURL:)
Source: https://piehost.com/docs/3.0/piesocket-swift
Create a `Channel` instance with a custom WebSocket URL to connect to third-party servers. Note that features like Private Channels, Presence Channels, and Multiple Rooms are not available.
```swift
Copy
let channel: Channel = Channel(webSocketURL: "wss://example.com", enabledLogs: true);
```
--------------------------------
### Publish WebSocket Event with wget
Source: https://piehost.com/docs/3.0/cli-websocket
Use this wget command to publish a JSON message to a WebSocket room. It uses a demo API key and secret, which are public and only for quick testing; do not use them in your application.
```bash
Copy# Demo Cluster ID, API key and secret used, get yours at https://piesocket.com
wget --no-check-certificate --quiet \
--method POST \
--timeout=0 \
--header 'Content-Type: application/json' \
--body-data '{
"key": "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm",
"secret": "d8129f82f8dd71910aa4a7efa30a7297",
"roomId": "room_1",
"message": {"event":"new-message","data":"Hello"}
}' \
'https://CLUSTER_ID.piesocket.com/api/publish'
```
--------------------------------
### Subscribe to a channel with join()
Source: https://piehost.com/docs/3.0/piesocket-android
Subscribe to a channel by calling join() on the PieSocket instance with the room ID. The returned Channel object is used for listening to events and publishing messages.
```java
Channel channel = piesocket.join("chat-room");
```
--------------------------------
### Change all ports at once with --port
Source: https://piehost.com/docs/3.0/piesocket-onprem
Use --port to set a base port. The server assigns the next two ports automatically: WebSocket → 8000, Publisher → 8001, Dashboard → 8002.
```bash
pie socket serve --port 8000
# WebSocket → 8000, Publisher → 8001, Dashboard → 8002
```
--------------------------------
### Add npm global bin to PATH (macOS/Linux)
Source: https://piehost.com/docs/3.0/piesocket-onprem
Fix 'command not found' by adding the npm global bin directory to PATH. Add this line to ~/.bashrc, ~/.zshrc, or ~/.profile to make it permanent.
```bash
export PATH="$(npm bin -g):$PATH"
```
--------------------------------
### Publish new_joining event on open
Source: https://piehost.com/docs/3.0/websocket-example
Publishes a new_joining event after the WebSocket connection is established. Generates a random username and sends it to the room to notify others of the new participant.
```javascript
Copyvar username = `user_${getRandomNumber()}`
piesocket.onopen = function() {
console.log(`Websocket connected`);
//Let others know I have arrived!
piesocket.send(JSON.stringify({
event: 'new_joining',
sender: username,
}));
}
```
--------------------------------
### PieMongo connection string
Source: https://piehost.com/docs/3.0/overview
Connection string for PieMongo, shown in the dashboard. Use it to connect to the managed MongoDB instance.
```text
mongodb://YOUR_USER:YOUR_PASSWORD@your-mongo.piehost.com:27017/?tls=true&tlsInsecure=true
```
--------------------------------
### Create NewOrder event with php artisan make:event
Source: https://piehost.com/docs/3.0/piesocket-laravel
Run this artisan command to generate a new event class named NewOrder. The event will be created in app/Events/NewOrder.php.
```bash
php artisan make:event NewOrder
```
--------------------------------
### Stand-alone usage with Channel.connect
Source: https://piehost.com/docs/3.0/flutter-websocket
Connects to a third-party WebSocket server by skipping the configuration part and creating a Channel instance. Note that features like Private Channels, Presence Channels, and Multiple Rooms are not available in stand-alone usage.
```dart
CopyChanel channel = Channel.connect("wss://example.com", true)
```
--------------------------------
### Subscribe to a Channel
Source: https://piehost.com/docs/3.0/piesocket-swift
Join a channel using a room ID. The room ID is required to publish messages from your server.
```swift
let channel: Channel = piesocket.join(roomId: "chat-room");
```
--------------------------------
### PieCache connection string
Source: https://piehost.com/docs/3.0/overview
Connection string for PieCache, shown in the dashboard. Use it to connect to the managed Redis instance.
```text
rediss://:YOUR_PASSWORD@your-cache.piehost.com:6380
```
--------------------------------
### Publish a message to a WebSocket Channel Room with Go
Source: https://piehost.com/docs/3.0/go-websocket
Use this Go code to publish a message to a WebSocket Channel Room via the PieHost API. It sends a POST request to the /api/publish endpoint with a JSON payload containing a demo key, secret, roomId, and message. The demo key and secret are public and for quick testing only; do not use them in production.
```go
package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
)
func main() {
url := "https://CLUSTER_ID.piesocket.com/api/publish"
method := "POST"
//Demo secret and key, get yours at piesocket.com
payload := strings.NewReader("{\n \"key\": \"oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm\",\n \"secret\": \"d8129f82f8dd71910aa4a7efa30a7297\",\n \"roomId\": 1,\n \"message\": \"Hello world!\"\n}")
client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
}
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}
```
--------------------------------
### Connect to WebSocket server with JavaScript
Source: https://piehost.com/docs/3.0/websocket-example
Add this JavaScript inside a script tag to connect to the WebSocket Room. Uses the demo API key and room ID 1.
```javascript
var apiKey = 'oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm';
var roomId = 1;
var piesocket = new WebSocket(`wss://demo.piesocket.com/v3/${roomId}?api_key=${apiKey}¬ify_self`);
```
--------------------------------
### Import PieSocket Channels
Source: https://piehost.com/docs/3.0/piesocket-swift
Import the Channels module to use PieSocket in your Swift application.
```swift
import Channels
```
--------------------------------
### Point Pusher SDK to self-hosted server (JavaScript)
Source: https://piehost.com/docs/3.0/piesocket-onprem
Configures the official Pusher JavaScript SDK to connect to the self-hosted server. The cluster value is required by the SDK but ignored by the server; set wsHost and wsPort to your server's host and port 4001.
```javascript
const pusher = new Pusher('your-app-key', {
wsHost: 'your-server-host',
wsPort: 4001,
forceTLS: false,
cluster: 'mt1', // required by SDK but ignored by the server
});
```
--------------------------------
### Listen to an Event
Source: https://piehost.com/docs/3.0/piesocket-swift
Attach a listener to an event. Multiple listeners can be added for the same event; all will be called when the event fires.
```swift
channel.listen(eventName: "new_message", callback: {event in
print(event.getData())
})
```
--------------------------------
### Add chat UI HTML
Source: https://piehost.com/docs/3.0/websocket-example
Add this HTML to build a minimal chat UI with a chat log and a form for sending messages.
```html
```
--------------------------------
### Add PieSocket Channels package
Source: https://piehost.com/docs/3.0/piesocket-flutter
Run this command in your Flutter project to add the piesocket_channels package.
```bash
flutter pub add piesocket_channels
```
--------------------------------
### SSH into PieBox server
Source: https://piehost.com/docs/3.0/overview
SSH command to connect to your PieBox server after launch. Replace YOUR_SERVER_IP with the server's IP address.
```bash
ssh root@YOUR_SERVER_IP
```
--------------------------------
### Subscribe to a channel
Source: https://piehost.com/docs/3.0/piesocket-flutter
Join a channel using the join method with a room ID. The room ID is needed to publish messages from your server.
```dart
Channel channel = piesocket.join("chat-room");
```
--------------------------------
### Enable presence in PieSocket
Source: https://piehost.com/docs/3.0/javascript-websocket
Enables presence features on a room, allowing you to see who is in the room and track when members join or leave via system:member_joined events.
```javascript
var pieSocket = new PieSocket({
...
presence: true
});
```
--------------------------------
### Import PieSocket Channels
Source: https://piehost.com/docs/3.0/piesocket-flutter
Import the PieSocket Channels package in your Dart file to use the SDK.
```dart
import 'package:piesocket_channels/channels.dart';
```