Skip to content

ytsoni/PhpSocketPackage

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

5 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PHP Socket Package

A comprehensive, enterprise-level PHP socket library built with Object-Oriented Programming (OOP) principles, SOLID design patterns, and modular architecture. This library provides a complete solution for socket communication in PHP applications with support for multiple protocols, event-driven architecture, and extensive configuration options.

PHP Version License PSR-4 PSR-3

πŸš€ Features

Core Architecture

  • βœ… SOLID Principles: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion
  • βœ… PSR-4 Autoloading: Fully compliant with PSR-4 namespace standards
  • βœ… PSR-3 Logging: Compatible with any PSR-3 compliant logger
  • βœ… Design Patterns: Factory, Observer, Template Method, Strategy patterns
  • βœ… Modular Design: Each component is independently testable and replaceable

Socket Functionality

  • βœ… TCP/UDP Support: Full support for both TCP and UDP protocols
  • βœ… IPv4/IPv6 Compatible: Works with both IPv4 and IPv6 addresses
  • βœ… Server & Client Modes: Complete server and client implementations
  • βœ… Non-blocking Operations: Support for both blocking and non-blocking I/O
  • βœ… Connection Management: Advanced connection pooling and lifecycle management
  • βœ… Broadcasting: Efficient message broadcasting to multiple clients

Protocol Support

  • βœ… Multiple Protocols: Raw, JSON, XML protocol handlers
  • βœ… Message Framing: Automatic message length prefixing for reliable transmission
  • βœ… Custom Protocols: Easy to extend with custom protocol handlers
  • βœ… Data Validation: Built-in validation for protocol-specific data

Event System

  • βœ… Event-Driven Architecture: Complete observer pattern implementation
  • βœ… Custom Events: Define and dispatch custom socket events
  • βœ… Event Priorities: Control event listener execution order
  • βœ… Event Propagation: Support for stopping event propagation

Configuration Management

  • βœ… Multiple Formats: Support for PHP, JSON, and INI configuration files
  • βœ… Environment-Specific: Different configurations for dev/test/production
  • βœ… Validation: Built-in configuration validation with schemas
  • βœ… Hot Reloading: Runtime configuration updates

Enterprise Features

  • βœ… Comprehensive Logging: Detailed logging with multiple handlers
  • βœ… Error Handling: Well-defined exception hierarchy
  • βœ… Statistics & Monitoring: Built-in metrics and connection statistics
  • βœ… Timeout Controls: Configurable timeouts for all operations
  • βœ… Retry Logic: Automatic retry with exponential backoff

πŸ“‹ Requirements

  • PHP 7.0 or higher
  • ext-sockets extension
  • ext-json extension
  • PSR-3 compatible logger (optional)

πŸ“¦ Installation

Via Composer (Recommended)

composer require ytsoni/phpsocketpackage

Manual Installation

  1. Download the package
  2. Include the autoloader:
require_once 'path/to/PhpSocketPackage/vendor/autoload.php';

πŸ—οΈ Architecture Overview

PhpSocketPackage/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ Contracts/           # Interfaces defining contracts
β”‚   β”œβ”€β”€ Core/               # Abstract base classes
β”‚   β”œβ”€β”€ Server/             # Server implementations
β”‚   β”œβ”€β”€ Client/             # Client implementations
β”‚   β”œβ”€β”€ Connection/         # Connection management
β”‚   β”œβ”€β”€ Protocol/           # Protocol handlers
β”‚   β”œβ”€β”€ Events/             # Event system
β”‚   β”œβ”€β”€ Config/             # Configuration management
β”‚   β”œβ”€β”€ Logging/            # Logging components
β”‚   β”œβ”€β”€ Exceptions/         # Exception hierarchy
β”‚   └── SocketFactory.php   # Main factory class
β”œβ”€β”€ config/                 # Configuration files
β”œβ”€β”€ examples/               # Usage examples
β”œβ”€β”€ tests/                  # Unit tests
└── docs/                   # Documentation

πŸš€ Quick Start

Simple Server

<?php
use PhpSocketPackage\SocketFactory;

// Create factory
$factory = new SocketFactory();

// Create and start server with JSON protocol
$server = SocketFactory::quickServer('127.0.0.1', 8080, 'json');

echo "Server started on 127.0.0.1:8080\n";

while (true) {
    $connection = $server->accept();
    if ($connection) {
        $data = $connection->receive();
        $connection->send(['echo' => $data]);
    }
}
?>

Simple Client

<?php
use PhpSocketPackage\SocketFactory;

// Create and connect client
$client = SocketFactory::quickClient('127.0.0.1', 8080, 'json');

// Send message
$client->send(['message' => 'Hello, Server!']);

// Receive response
$response = $client->receive();
echo json_encode($response, JSON_PRETTY_PRINT);
?>

πŸ“– Detailed Usage

Using the Factory Pattern

<?php
use PhpSocketPackage\SocketFactory;
use PhpSocketPackage\Config\Configuration;

// Load configuration
$config = new Configuration();
$config->load('config/socket.php');

// Create factory with configuration
$factory = new SocketFactory($config);

// Create server with custom options
$server = $factory->createServer([
    'protocol_handler' => 'json',
    'max_connections' => 1000,
    'connection_timeout' => 300
]);

// Start server
$server->start('0.0.0.0', 8080);
?>

Event-Driven Programming

<?php
use PhpSocketPackage\Events\SocketEvent;

// Register event listeners
$factory->getEventDispatcher()->listen('connection.accepted', function (SocketEvent $event) {
    $connection = $event->get('connection');
    echo "New client: {$connection->getRemoteAddress()}\n";
});

$factory->getEventDispatcher()->listen('server.broadcast', function (SocketEvent $event) {
    $results = $event->get('results');
    echo "Broadcasted to " . count($results) . " clients\n";
});
?>

Custom Protocol Handler

<?php
use PhpSocketPackage\Protocol\AbstractProtocolHandler;

class CustomProtocolHandler extends AbstractProtocolHandler
{
    protected $name = 'custom';
    protected $contentType = 'application/custom';
    
    public function encode($data): string
    {
        // Custom encoding logic
        return base64_encode(serialize($data));
    }
    
    public function decode(string $data)
    {
        // Custom decoding logic
        return unserialize(base64_decode($data));
    }
    
    public function validate($data): bool
    {
        // Custom validation logic
        return true;
    }
}

// Register custom protocol
$factory->registerProtocolHandler('custom', new CustomProtocolHandler());
?>

Advanced Server with Connection Management

<?php
use PhpSocketPackage\SocketFactory;

$factory = new SocketFactory();
$server = $factory->createServer([
    'protocol_handler' => 'json',
    'max_connections' => 100
]);

$server->start('127.0.0.1', 8080);

$clients = [];

while (true) {
    // Accept new connections (non-blocking)
    $newConnection = $server->acceptNonBlocking();
    if ($newConnection) {
        $clients[$newConnection->getId()] = $newConnection;
        echo "Client connected: " . $newConnection->getId() . "\n";
    }
    
    // Handle existing clients
    foreach ($clients as $clientId => $client) {
        if (!$client->isActive()) {
            unset($clients[$clientId]);
            continue;
        }
        
        try {
            $data = $client->receive(1024, MSG_DONTWAIT);
            if ($data) {
                // Process message
                $response = ['echo' => $data, 'timestamp' => time()];
                $client->send($response);
            }
        } catch (Exception $e) {
            echo "Client error: " . $e->getMessage() . "\n";
            unset($clients[$clientId]);
        }
    }
    
    usleep(10000); // 10ms delay
}
?>

Configuration Management

<?php
use PhpSocketPackage\Config\Configuration;

// Create configuration
$config = new Configuration();

// Load from file
$config->load('config/socket.php');

// Set environment
$config->setEnvironment('production');

// Get environment-specific values
$port = $config->env('server.port', 8080);
$address = $config->env('server.address', '127.0.0.1');

// Validate configuration
if (!$config->validate()) {
    throw new Exception('Invalid configuration');
}
?>

Logging Integration

<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use PhpSocketPackage\SocketFactory;

// Create PSR-3 compatible logger
$logger = new Logger('socket');
$logger->pushHandler(new StreamHandler('socket.log', Logger::DEBUG));

// Create factory with logger
$factory = new SocketFactory(null, $logger);

// All socket operations will be logged
$server = $factory->createServer();
?>

πŸ§ͺ Examples

The package includes comprehensive examples in the examples/ directory:

  • basic_server.php - Simple echo server with JSON protocol
  • basic_client.php - Interactive client with command support
  • advanced_server.php - Multi-client server with broadcasting
  • custom_protocol.php - Custom protocol implementation
  • event_driven.php - Event-driven server example
  • configuration.php - Configuration management example

Running Examples

# Terminal 1 - Start server
php examples/basic_server.php

# Terminal 2 - Start client
php examples/basic_client.php

πŸ”§ Configuration

Configuration File Structure

<?php
return [
    'socket' => [
        'domain' => AF_INET,
        'type' => SOCK_STREAM,
        'protocol' => SOL_TCP,
        'timeout' => 30
    ],
    'server' => [
        'address' => '127.0.0.1',
        'port' => 8080,
        'backlog' => 128,
        'max_connections' => 1000
    ],
    'client' => [
        'retry_attempts' => 3,
        'retry_delay' => 1000
    ],
    'protocol' => [
        'default' => 'json',
        'handlers' => [
            'json' => [
                'frame_messages' => true,
                'max_message_size' => 1048576
            ]
        ]
    ],
    'environments' => [
        'development' => [
            'logging' => ['level' => 'debug']
        ],
        'production' => [
            'logging' => ['level' => 'error']
        ]
    ]
];
?>

πŸ§ͺ Testing

# Run all tests
composer test

# Run with coverage
composer test-coverage

# Code style check
composer cs-check

# Static analysis
composer analyse

πŸ“Š Performance

The library is designed with performance considerations:

  • Efficient Memory Usage: Minimal memory footprint per connection object
  • Non-blocking I/O Options: Support for non-blocking socket operations
  • Connection Pooling: Basic connection management and reuse
  • Optimized Protocol Handlers: Efficient JSON/XML/Raw data processing
  • Event System: Lightweight event dispatching mechanism

Performance Characteristics

Note: Actual performance depends on hardware, PHP version, message size, and application logic.

Aspect Typical Range Notes
Concurrent Connections 100-1,000 Depends on server resources and socket limits
Messages/Second 1,000-10,000 Varies with message size and protocol complexity
Memory per Connection 5-20KB Includes connection object and protocol overhead
Basic Echo Latency <1ms Local network, minimal processing

Performance Tips

  • Use non-blocking I/O for concurrent connections
  • Implement proper connection pooling for high-throughput scenarios
  • Choose appropriate protocol handlers (Raw > JSON > XML for speed)
  • Configure proper socket timeouts and buffer sizes
  • Monitor memory usage with many concurrent connections

πŸ”¬ Benchmarking

The package includes comprehensive benchmarking tools to measure performance:

Quick Performance Check

php benchmarks/quick_benchmark.php

Detailed Protocol Comparison

php benchmarks/protocol_benchmark.php

Load Testing (with concurrent connections)

php benchmarks/load_test.php

Complete Performance Analysis

php benchmarks/run_all_benchmarks.php

See benchmarks/README.md for detailed benchmarking documentation.

πŸ›‘οΈ Security Considerations

  • Input Validation: All protocol handlers validate input data
  • Buffer Overflow Protection: Configurable message size limits
  • Resource Limits: Connection and memory limits
  • Error Handling: Secure error reporting without information leakage
  • XML External Entity: Protection against XXE attacks in XML protocol

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

# Clone repository
git clone https://github.com/ytsoni/phpsocketpackage.git

# Install dependencies
composer install

# Run tests
composer test

# Check code style
composer cs-check

πŸ“„ License

This project is licensed under the MIT License. See the LICENSE file for details.

πŸ†˜ Support

🎯 Roadmap

  • WebSocket Support - Native WebSocket protocol implementation
  • HTTP/2 Support - HTTP/2 protocol handler
  • SSL/TLS Support - Secure socket communication
  • Message Queuing - Built-in message queue integration
  • Cluster Support - Multi-server socket clustering
  • Performance Dashboard - Real-time monitoring interface
  • Docker Images - Pre-built Docker containers
  • Kubernetes Helm Charts - Easy deployment to Kubernetes

πŸ™ Acknowledgments

  • PHP Community for excellent documentation and standards
  • PSR Working Group for standardization efforts
  • Contributors and users who help improve this library

Made with ❀️ by the PHP Socket Package Team

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages