PHP code example of initphp / socket

1. Go to this page and download the library: Download initphp/socket library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

initphp / socket example snippets

 
public static function server(int $handler = Socket::TCP, string $host = '', int $port = 0, null|string|float $argument = null): \InitPHP\Socket\Interfaces\SocketServerInterface
 
public static function client(int $handler = self::TCP, string $host = '', int $port = 0, null|string|float $argument = null): \InitPHP\Socket\Interfaces\SocketClientInterface
 
public function connection(): self;
 
public function disconnect(): bool;
 
public function read(int $length = 1024): ?string;
 
public function write(string $string): ?int;
 
public function live(callable $callback): void;
 
public function wait(int $second): void;

public function broadcast(string $message, array|string|int|null $clients = null): bool;

public function timeout(int $second): self;

public function blocking(bool $mode = true): self;

public function crypto(?string $method = null): self;

public function option(string $key, mixed $value): self;


use \InitPHP\Socket\Socket;
use \InitPHP\Socket\Interfaces\{SocketServerInterface, SocketServerClientInterface};

$server = Socket::server(Socket::TLS, '127.0.0.1', 8080);
$server->connection();

$server->live(function (SocketServerInterface $socket, SocketServerClientInterface $client) {
    $read = $client->read();
    if (!$read) {
        return;
    }
    if (in_array($read, ['exit', 'quit'])) {
            $client->push("Goodbye!");
            $client->close();
        return;
    } else if (preg_match('/^REGISTER\s+([\w]{3,})$/i', $read, $matches)) {
        // REGISTER admin
        $name = trim(mb_substr($read, 9));
        $socket->clientRegister($name, $client);
    } else if (preg_match('/^SEND\s@([\w]+)\s(.*)$/i', $read, $matches)) {
        // SEND @admin Hello World
        $pushSocketName = $matches[1];
        $message = $matches[2];
        $socket->broadcast($message, [$pushSocketName])
    } else {
        $message = trim($read);
        !empty($message) && $socket->broadcast($message);
    }
});


use \InitPHP\Socket\Socket;

$client = Socket::client(Socket::SSL, 'smtp.gmail.com', 465);

$client->option('verify_peer', false)
    ->option('verify_peer_name', false);

$client->connection();

$client->write('EHLO [127.0.0.1]');

echo $client->read();