PHP code example of wheakerd / sse-client

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

    

wheakerd / sse-client example snippets



declare(strict_types=1);

namespace App\Controller;

use Wheakerd\SseClient\Client;


final class IndexController
{
    public function index()
    {
        $client = new Client('https://www.example.com', 0.5);
        
        if (!$client->isConnected()) {
            return '无法连接到服务器';
        }
        
        //  如果第三方要求鉴权
        $sseClient->setHeader('Authorization', 'Bearer your token');
        
        $res = $sseClient->send(
			[
				'data' => '...',
			],
		);
		
		//  如果发送失败
		if (false === $send) {
		    //  获取错误原因
			return $client->sta();
		}
		
		while (true) {
			$chunk = $client->recv();
			
			//  全等于空 直接关闭连接
			if ('' === $chunk) {
			    $client->close();
			}
			
			$chunkData = $client->decode($chunk);

			if (null === $chunkData) {
				continue;
			}
			if (false === $chunkData) {
				break;
			}

			$eventStreamResponse->success('message', $chunk);
		}

		$eventStreamResponse->close();
    }
}