Skip to content

Commit

Permalink
Optimize UdpSocketAspect (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
huangdijia authored Dec 10, 2022
1 parent c047dbf commit 9a35dcc
Showing 1 changed file with 5 additions and 24 deletions.
29 changes: 5 additions & 24 deletions src/Aspect/UdpSocketAspect.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,39 +13,20 @@
use Hyperf\Context\Context;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\Engine\Socket;
use Hyperf\Utils\Coroutine;
use Monolog\Handler\SyslogUdp\UdpSocket;

class UdpSocketAspect extends AbstractAspect
{
public array $classes = [
UdpSocket::class . '::send',
UdpSocket::class . '::close',
UdpSocket::class . '::getSocket',
];

public function process(ProceedingJoinPoint $proceedingJoinPoint)
{
if (Coroutine::inCoroutine()) {
if ($proceedingJoinPoint->methodName == 'close') {
return;
}
[$ip, $port] = (fn () => [$this->ip, $this->port])->call($proceedingJoinPoint->getInstance());
(fn () => $this->socket = null)->call($proceedingJoinPoint->getInstance());
$key = sprintf('%s_%s_%s_%s', $proceedingJoinPoint->className, 'Socket', $ip, $port);

/** @var string $chunk */
$chunk = $proceedingJoinPoint->arguments['keys']['chunk'] ?? '';
[$ip, $port] = (fn () => [$this->ip, $this->port])->call($proceedingJoinPoint->getInstance());

$key = sprintf('%s_%s_%s_%s', $proceedingJoinPoint->className, 'Socket', $ip, $port);
$socket = Context::getOrSet($key, fn () => tap(new Socket(AF_INET, SOCK_DGRAM, SOL_UDP), function (Socket $socket) use ($ip, $port) {
$socket->connect($ip, $port, 0.5);
defer(fn () => $socket->isClosed() || $socket->close());
}));

$socket->send($chunk);

return;
}

return $proceedingJoinPoint->process();
return Context::getOrSet($key, fn () => $proceedingJoinPoint->process());
}
}

0 comments on commit 9a35dcc

Please sign in to comment.