Skip to content

kadekdodikwirawan/wsocket

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

WSocket - WebSocket Server

A lightweight WebSocket server written in C++ with both standalone binary and PHP extension support. Features a beautiful Tailwind CSS chat UI and supports Cloudflare Tunnel for public access.

Features

  • 🚀 Standalone Binary - Run without PHP, no dependencies on shared hosting
  • 🐘 PHP Extension - Use in PHP with new WSocket(port) syntax
  • 💬 Built-in Chat UI - Beautiful Tailwind CSS chat room served via HTTP
  • 🔄 Event System - Socket.IO-like emit/on pattern
  • 🌐 Cloudflare Tunnel - Works with wss:// through tunnels
  • 👥 User Tracking - Online count, join/leave notifications
  • 📡 Event Forwarding - Broadcast or send to specific clients

Requirements

Standalone Binary

  • g++ with C++17 support
  • OpenSSL development headers (libssl-dev)

PHP Extension (optional)

  • PHP 8.x with development headers (php-dev)
  • PHP-CPP library (libphpcpp)

Building

# Build everything (PHP extension + standalone binary)
make

# Build only standalone binary
make wsocket

# Build static binary (for shared hosting without OpenSSL)
make static

Quick Start

Standalone Server

# Start server on port 8080
./wsocket 8080

# Open in browser
# http://localhost:8080

The server automatically serves client.html when accessed via HTTP browser.

With Cloudflare Tunnel

# Terminal 1: Start server
./wsocket 8080

# Terminal 2: Create tunnel
cloudflared tunnel --url http://localhost:8080

# Access via the tunnel URL (e.g., https://xxx.trycloudflare.com)

PHP Extension Usage

<?php
// Create server (singleton per port)
$ws = new WSocket(8080);

// Event handlers
$ws->onConnect(function($clientId) {
    echo "Client $clientId connected\n";
});

$ws->onMessage(function($clientId, $message) use ($ws) {
    $ws->broadcast("Client $clientId: $message");
});

// Start server
$ws->start();

// Messaging
$ws->emit('notification', '{"message":"Hello!"}');  // To all
$ws->emitTo(1, 'private', '{"text":"Hi"}');         // To specific client
$ws->broadcast('Raw message to all');

// Get info
echo $ws->getClientCount();
print_r($ws->getClientIds());

Standalone Server Commands

When running the standalone server, use these commands:

Command Description
emit <event> <json> Emit event to all clients
broadcast <message> Send raw message to all
sendto <id> <message> Send to specific client
emitto <id> <event> <json> Emit to specific client
clients Show connected clients
quit Stop server

Client Event Format

Events are JSON messages:

// Send event (browser)
ws.send(JSON.stringify({
    event: 'chat',
    data: { message: 'Hello!' },
    to: 2  // Optional: specific client ID
}));

// Receive event
ws.onmessage = (e) => {
    const msg = JSON.parse(e.data);
    // msg.event = 'chat'
    // msg.data = { from: 1, payload: { message: 'Hello!' } }
};

System Events

Event Direction Description
_connected Server → Client Sent on connect with {clientId: N}
_userCount Server → Client Broadcast when user count changes

Project Structure

├── common/
│   ├── wsocket_common.h      # Shared WebSocket server header
│   └── wsocket_common.cpp    # Shared implementation
├── wsocket_main.cpp          # Standalone binary entry point
├── wsocket_php.cpp           # PHP extension wrapper
├── client.html               # Chat UI (served via HTTP)
├── Makefile
└── README.MD

Make Commands

Command Description
make Build PHP extension + standalone binary
make wsocket Build standalone binary only
make static Build static binary (no dependencies)
make install Install PHP extension
make clean Remove built files

Deployment (Shared Hosting)

For shared hosting without root access:

# Build static binary
make static

# Upload to server
scp wsocket-static client.html user@server:~/

# On server
chmod +x wsocket-static
./wsocket-static 8080

API Reference

WebSocketServer Class

Server Control

  • start() - Start the server
  • stop() - Stop the server
  • isRunning() - Check if running
  • getPort() - Get port number

Messaging

  • broadcast(message) - Send raw message to all
  • broadcastExcept(message, excludeId) - Broadcast except one client
  • emit(event, data) - Emit event to all
  • emitExcept(event, data, excludeId) - Emit except one client
  • sendTo(clientId, message) - Send to specific client
  • emitTo(clientId, event, data) - Emit to specific client
  • forwardEvent(fromId, event, data, toId) - Forward client event

Client Management

  • getClientCount() - Get number of connected clients
  • getClientIds() - Get array of client IDs
  • setUsername(clientId, name) - Set client username
  • getUsername(clientId) - Get client username

Event Handlers (Standalone)

  • onConnect(callback) - Handle new connections
  • onDisconnect(callback) - Handle disconnections
  • onMessage(callback) - Handle messages

HTTP

  • setHttpContent(html) - Set HTML to serve on HTTP requests

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published