Installation
composer require clue/socket-raw
Ensure ext-sockets is enabled in your php.ini (extension=sockets).
Basic Usage
use Clue\React\Socket\Raw\Connector;
use React\EventLoop\Factory;
$loop = Factory::create();
$connector = new Connector($loop);
$connector->connect('tcp://127.0.0.1:8080')->then(
function ($socket) {
$socket->write('Hello, Server!');
$socket->on('data', function ($data) {
echo "Received: " . $data . "\n";
});
}
);
$loop->run();
First Use Case
TCP Client/Server
// Client
$connector->connect('tcp://example.com:1234')->then(function ($socket) {
$socket->write('PING');
});
// Server
$server = new Server($loop);
$server->listen('tcp://0.0.0.0:1234');
$server->on('connection', function ($socket) {
$socket->on('data', function ($data) use ($socket) {
$socket->write('ACK: ' . $data);
});
});
UDP Client/Server
// Client
$udpSocket = new Socket($loop, AF_INET, SOCK_DGRAM, SOL_UDP);
$udpSocket->send('UDP PING', '127.0.0.1', 5000);
// Server
$udpSocket->on('message', function ($data, $address) {
echo "UDP from {$address}: " . $data . "\n";
});
Integration with ReactPHP
Clue\React\Socket\Raw\Connector/Server with ReactPHP’s event loop for async I/O.React\Socket\ConnectionInterface for higher-level protocols (e.g., HTTP).Binary Data Handling
$socket->on('data', function ($binaryData) {
$unpacked = unpack('C*', $binaryData); // Convert binary to array
// Process binary protocol (e.g., Redis, custom binary formats)
});
$socket->setTimeout(5.0) to avoid hanging.error event:
$socket->on('error', function ($error) {
echo "Socket error: " . $error->getMessage() . "\n";
});
Blocking Calls
socket_* functions; always use async methods (e.g., write(), send()).Resource Leaks
$server->close();
$socket->close();
finally or React\Promise\Timer\timeout() to ensure cleanup.Protocol Mismatches
react/http for higher-level protocols.IPv6/Unix Domain Sockets
AF_INET6; Unix sockets use AF_UNIX:
$socket = new Socket($loop, AF_UNIX, SOCK_STREAM);
$socket->connect('/tmp/mysocket.sock');
$socket->on('debug', function ($message) {
error_log($message);
});
if ($socket->isWritable()) {
$socket->write('Data');
}
strace/tcpdump:
strace -f -e trace=network php your_script.php
Custom Protocols
Clue\React\Socket\Raw\Socket to add protocol-specific logic (e.g., encryption, compression).ReactPHP Integration
React\Promise for chaining:
$connector->connect('tcp://...')->then(function ($socket) {
return $socket->write('Data')->then(function () use ($socket) {
$socket->close();
});
});
Laravel Integration
spatie/react package) for async tasks:
use Spatie\Async\Async;
Async::onLoop(function () {
$loop = Factory::create();
// Socket logic here
$loop->run();
});
Performance Tuning
socket_set_nonblock() for high-throughput scenarios.How can I help you explore Laravel packages today?