1. Go to this page and download the library: Download friendsofhyperf/tcp-sender 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/ */
namespace App;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnReceiveInterface;
use FriendsOfHyperf\TcpSender\Sender;
use Swoole\Server;
class TcpServer implements OnCloseInterface,OnReceiveInterface
{
public function __construct(private Sender $sender)
{
}
/**
* @param Server $server
*/
public function onConnect($server, $fd, $reactorId): void
{
$server->send($fd, sprintf('Client %s connected.'.PHP_EOL, $fd));
}
public function onClose($server, int $fd, int $reactorId): void
{
$server->send($fd, sprintf('Client %s closed.'.PHP_EOL, $fd));
}
public function onReceive($server, int $fd, int $reactorId, string $data): void
{
$server->send($fd, sprintf('Client %s send: %s'.PHP_EOL, $fd, $data));
var_dump($data);
}
}
namespace App;
use Hyperf\Contract\OnReceiveInterface;
use FriendsOfHyperf\TcpSender\Sender;
use Swoole\Coroutine\Server\Connection;
use Swoole\Server;
class TcpServer implements OnReceiveInterface
{
public function __construct(private Sender $sender)
{
}
public function onConnect(Connection $connection, $fd): void
{
// 设置 fd 和 connection 的映射关系
$this->sender->setResponse($fd,$connection);
$connection->send(sprintf('Client %s connected.'.PHP_EOL, $fd));
}
public function onClose($connection, int $fd): void
{
// 删除 fd 和 connection 的映射关系
$this->sender->setResponse($fd,null);
}
public function onReceive($server, int $fd, int $reactorId, string $data): void
{
$server->send($fd, sprintf('Client %s send: %s'.PHP_EOL, $fd, $data));
}
}
declare(strict_types=1);
namespace App\Controller;
use FriendsOfHyperf\TcpSender\Sender;
class IndexController extends AbstractController
{
public function __construct(private Sender $sender)
{
}
public function index()
{
// 向指定的fd发送消息
$this->sender->send(1, 'Hello Hyperf.');
$user = $this->request->input('user', 'Hyperf');
$method = $this->request->getMethod();
return [
'method' => $method,
'message' => "Hello {$user}.",
];
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.