PHP code example of moebius / socket

1. Go to this page and download the library: Download moebius/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/ */

    

moebius / socket example snippets


use Moebius\Socket\Client;
use function M\{go, await};

/**
 * *** COROUTINE 1 ***
 */
$google = go(function() {
    $client = new Client('tcp://www.google.com:80');
    $client->write("GET / HTTP/1.0\r\n\r\n");
    while (!$client->eof()) {
        echo "< ".$client->readLine()."\n";
    }
});
/**
 * *** COROUTINE 2 ***
 */
$bing = go(function() {
    $client = new Client('tcp://www.bing.com:80');
    $client->write("GET / HTTP/1.0\r\n\r\n");
    while (!$client->eof()) {
        echo "< ".$client->readLine()."\n";
    }
});


/**
 * *** AWAIT BOTH COROUTINES ***
 */
await($google);
await($bing);

use Moebius\Socket\Server;
use function M\go;

$server = new Server('tcp://0.0.0.0:8080');
while ($connection = $server->accept()) {

    /**
     * *** LAUNCH A COROUTINE PER CONNECTION ***
     */
    go(function() use ($connection) {

        $requestLine = $connection->readLine();

        do {
            $header = $connection->readLine();
        } while ($header !== '');

        $connection->write(<<<RESPONSE
            HTTP/1.0 200 OK\r
            Content-Type: text/plain\r
            \r
            Hello World!
            RESPONSE);

        $connection->close();
            
    });
}


Moebius\Socket\Client;
use function M\{go, await};

// Asynchronous operation :80');
    $client->connect();
    $client->write("GET / HTTP/1.0\r\n\r\n");

    $buffer = ''

    while (!$client->eof()) {
        $buffer .= $client->read(4096);
    }

    return $buffer;
});

$futureBufferA = go(function() {

    $client = new Client('tcp://www.vg.no:80');
    $client->connect();
    $client->write("GET / HTTP/1.0\r\n\r\n");

    $buffer = ''

    while (!$client->eof()) {
        $buffer .= $client->read(4096);
    }

    return $buffer;
});


// note that it does not matter which order you await each of these buffers
$bufferA = await( $futureBufferA );
$bufferB = await( $futureBufferB );

echo "Received ".strlen($bufferA)." bytes from client A and ".strlen($bufferB)." bytes from client B\n";