PHP code example of spatie / simple-tcp-client

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

    

spatie / simple-tcp-client example snippets


use Spatie\SimpleTcpClient\TcpClient;

$client = new TcpClient('smtp.gmail.com', 587);

$client->connect();

$greeting = $client->receive();
echo $greeting; // 220 smtp.gmail.com ESMTP...

$client->send("EHLO test.local\r\n");
$response = $client->receive();
echo $response; // 250-smtp.gmail.com capabilities...

$client->close();

use Spatie\SimpleTcpClient\TcpClient;

$client = new TcpClient('example.com', 80);

$client->connect();

$client->send("Hello, server!");

$response = $client->receive(); // Read response from server

echo $response;

$response = $client->receive(1024);

use Spatie\SimpleTcpClient\TcpClient;
use Spatie\SimpleTcpClient\Exceptions\ConnectionTimeout;

$client = new TcpClient('slow-server.com', 80, 5_000); // 5000ms (5 second) timeout

try {
    $client->connect();
} catch (ConnectionTimeout $exception) {
    echo "Server took too long to respond: " . $exception->getMessage();
}

$client = new TcpClient('httpbin.org', 80);

$client->connect();

$request = "GET /get HTTP/1.1\r\n";
$request .= "Host: httpbin.org\r\n";
$request .= "Connection: close\r\n\r\n";

$client->send($request);

$response = $client->receive();

echo $response;

$client->close();

use Spatie\SimpleTcpClient\TcpClient;

$client = new TcpClient('smtp.gmail.com', 587);

$client->connect();

// Read the greeting
$greeting = $client->receive();
echo $greeting; // 220 smtp.gmail.com ESMTP...

// Send EHLO command
$client->send("EHLO test.local\r\n");
$response = $client->receive();
echo $response; // 250-smtp.gmail.com capabilities...

$client->close();

use Spatie\SimpleTcpClient\TcpClient;
use Spatie\SimpleTcpClient\Exceptions\CouldNotConnect;

try {
    $client = new TcpClient('8.8.8.8', 53);
    
    $client->connect();
    
    echo "Port 53 is open!";
    
    $client->close();
} catch (CouldNotConnect $exception) {
    echo "Port 53 is closed or filtered";
}