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.
- β 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
- β 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
- β 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-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
- β 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
- β 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
- PHP 7.0 or higher
- ext-sockets extension
- ext-json extension
- PSR-3 compatible logger (optional)
composer require ytsoni/phpsocketpackage- Download the package
- Include the autoloader:
require_once 'path/to/PhpSocketPackage/vendor/autoload.php';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
<?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]);
}
}
?><?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);
?><?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);
?><?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";
});
?><?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());
?><?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
}
?><?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');
}
?><?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();
?>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
# Terminal 1 - Start server
php examples/basic_server.php
# Terminal 2 - Start client
php examples/basic_client.php<?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']
]
]
];
?># Run all tests
composer test
# Run with coverage
composer test-coverage
# Code style check
composer cs-check
# Static analysis
composer analyseThe 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
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 |
- 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
The package includes comprehensive benchmarking tools to measure performance:
php benchmarks/quick_benchmark.phpphp benchmarks/protocol_benchmark.phpphp benchmarks/load_test.phpphp benchmarks/run_all_benchmarks.phpSee benchmarks/README.md for detailed benchmarking documentation.
- 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
We welcome contributions! Please see our Contributing Guide for details.
# Clone repository
git clone https://github.com/ytsoni/phpsocketpackage.git
# Install dependencies
composer install
# Run tests
composer test
# Check code style
composer cs-checkThis project is licensed under the MIT License. See the LICENSE file for details.
- Issues: GitHub Issues
- Documentation: Full Documentation
- Examples: Check the
examples/directory - Community: Discussions
- 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
- 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