Links:
Dependencies:
This example server creates a socket, listens and outputs any data written to it.
server.php
$host = "0.0.0.0";
$port = 5555;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if( $socket === false )
{
die("Socket creation failed: " . socket_strerror(socket_last_error()) . "\n");
}
if( !socket_bind($socket, $host, $port ) )
{
die("Socket bind failed: " . socket_strerror(socket_last_error($socket)) . "\n");
}
if( !socket_listen( $socket, 5 ) )
{
die("Socket listen failed: " . socket_strerror(socket_last_error($socket)) . "\n");
}
echo "Listening on $host:$port...\n";
while( true )
{
$client = socket_accept( $socket );
if( $client === false )
{
echo "Socket accept failed: " . socket_strerror(socket_last_error($socket)) . "\n";
continue;
}
$input = socket_read( $client, 1024 );
if( $input === false )
{
echo "Socket read failed: " . socket_strerror(socket_last_error($client)) . "\n";
}
else
{
echo "Received: " . trim( $input ) . "\n";
}
socket_close( $client );
}
This client sends all logs to a socket server in the JSON format.
client.php
use Neuron\Log\ILogger;
use php\logging\src\Log\Logger;
use Neuron\Log\Destination;
use Neuron\Log\Format;
require 'vendor/autoload.php';
$Socket = new Destination\Socket( new Format\JSON() );
$Socket->open(
[
'ip_address' => '127.0.0.1',
'port' => 5555,
]
);
$Log = new Logger( $Socket );
$Log->setRunLevel( ILogger::DEBUG );
$Log->setContext( 'version', '0.5' );
$Log->info( 'Hello World' );
Start the server:
php server.php
The server will run until terminated.
In another terminal window, run the client:
php client.php
The server should output:
Listening on 0.0.0.0:5555...
Received: {"date":"2025-01-11 20:41:48","level":"Info","context":"version=0.5","text":"Hello World"}