server/app/Service/Message/Channel/WebsocketChannel.php

90 lines
2.2 KiB
PHP

<?php
namespace App\Service\Message\Channel;
use App\Model\Account;
use App\Model\Message;
use App\Model\Online as oModel;
use App\Service\Message\Exception\ChannelFailException;
use App\Service\Message\Interface\ChannelInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\WebSocketServer\Sender;
use function Hyperf\Coroutine\go;
class WebsocketChannel implements ChannelInterface
{
#[Inject]
protected Sender $sender;
public function send(Account $account, Message $message): bool
{
try {
$lines = oModel::getFds($account->account_id);
foreach ($lines as $fd) {
$this->sendOk($fd, $message->title, $message->type, $message->extra);
}
return true;
} catch (\Exception $exception) {
throw new ChannelFailException($exception->getMessage());
}
}
public function getName(): string
{
return "websocket";
}
/**
* 推送信息
* Author: cfn <cfn@leapy.cn>
* @param int $fd
* @param string $msg
* @param string $type
* @param string|null $extra
* @return void
*/
public function sendOk(int $fd, string $msg, string $type = "msg", string $extra = null): void
{
$resp = [
'code' => 200,
'msg' => $msg,
'type' => $type,
'extra' => $extra
];
$this->sender->push($fd, json_encode($resp, true));
}
/**
* 推送信息
* Author: cfn <cfn@leapy.cn>
* @param int $fd
* @param string $msg
* @param string $type
* @param string|null $extra
* @return void
*/
public function sendErr(int $fd, string $msg, string $type = "msg", string $extra = null): void
{
$resp = [
'code' => 400,
'msg' => $msg,
'type' => $type,
'extra' => $extra
];
$this->sender->push($fd, json_encode($resp, true));
}
/**
* 关闭连接
* Author: cfn <cfn@leapy.cn>
* @param int $fd
* @return void
*/
public function close(int $fd): void
{
go(function () use ($fd) {
sleep(1);
$this->sender->disconnect($fd);
});
}
}