PHP code example of kzykhys / coroutine-io

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

    

kzykhys / coroutine-io example snippets


php example.php
 php


use CoroutineIO\Example\HttpHandler;
use CoroutineIO\Example\HttpServer;

 php


namespace CoroutineIO\Example;

use CoroutineIO\Exception\Exception;
use CoroutineIO\Server\Server;

/**
 * Simple HTTP Server Implementation
 */
class HttpServer extends Server
{

    /**
     * {@inheritdoc}
     */
    public function createSocket($address = 'localhost:8000')
    {
        $socket = @stream_socket_server('tcp://' . $address, $no, $str);

        if (!$socket) {
            throw new Exception("$str ($no)");
        }

        return $socket;
    }

}
 php


namespace CoroutineIO\Example;

use CoroutineIO\Server\HandlerInterface;
use CoroutineIO\Socket\ProtectedStreamSocket;
use CoroutineIO\Socket\StreamSocket;

/**
 * Simple HTTP Server Implementation
 */
class HttpHandler implements HandlerInterface
{

    /**
     * {@inheritdoc}
     */
    public function handleClient(StreamSocket $socket)
    {
        $socket->block(false);
        $data = (yield $socket->read(8048));

        $response = $this->handleRequest($data, new ProtectedStreamSocket($socket));

        yield $socket->write($response);
        yield $socket->close();
    }

    /**
     * {@inheritdoc}
     */
    public function handleRequest($input, ProtectedStreamSocket $socket)
    {
        // Displays request information
        echo $socket->getRemoteName() . "\n";
        echo $input;

        return "HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-Length: 5\n\nHello";
    }

}