PHP code example of matasarei / php-tcp

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

    

matasarei / php-tcp example snippets


use Matasar\PhpTcp\Client;
use Matasar\PhpTcp\Request;
use Matasar\PhpTcp\Socket\StreamSocket;

$client = new Client('ip_or_hostname', 8888, new StreamSocket());
$client->connect();

$response = $client->request(new Request('request data'));
$client->disconnect();

var_dump($response->getData());

$request = new Request('request data', 5);

use Matasar\PhpTcp\Socket\FSocket;

new FSocket(2);        // wait up to 2 seconds per read cycle
new FSocket(0);        // non-blocking mode
new FSocket(2, false); // non-blocking, but still a 2 second read timeout

use Matasar\PhpTcp\Client;
use Matasar\PhpTcp\Socket\FSocket;

$client = new Client('hostname', 1234, new FSocket());

$client->setChunkSize(16384);          // read data by 16 KB per cycle (default 8 KB).
$client->setPollInterval(5000);        // wait 5 ms between data availability checks (default 1 ms).
$client->setDelimiter("\n");           // treat "\n" as the end of a response (see below).
$client->setMaxResponseSize(65536);    // refuse a response over 64 KB (default 8 MiB, null for no limit).
$client->setLogger(new PsrLogger());   // any PSR-3 logger, for debugging.

$client->connect(5);   // connection timeout in seconds (default 2).
$client->connect(0.5); // fractions are allowed.

$client->setDelimiter("\n");

use Matasar\PhpTcp\Exception\ConnectionException;
use Matasar\PhpTcp\Exception\RequestException;

try {
    $client->connect();
    $response = $client->request($request);
} catch (ConnectionException $exception) {
    // failed to connect / connection lost
} catch (RequestException $exception) {
    // the server did not respond in time
}
bash
composer