php websocket测试,定时检测websocket服务

use Swoole\Table;

use Swoole\Timer;

use Swoole\Coroutine\Http\Client;

class CheckPos

{

/**

* 定时器间隔时间

*/

const TIMER_INTERVAL = 30 * 60 * 1000;

/**

* 异常邮件触发间隔

*/

const EMAIL_INTERVAL = 10 * 60;

private $table;

public function __construct()

{

date_default_timezone_set('Asia/Shanghai');

$this->table = $this->createTable();

}

private function createTable()

{

$table = new Table(1024);

$table->column('send_time', Table::TYPE_STRING, 10);

$table->create();

return $table;

}

public function schedule()

{

Timer::tick(self::TIMER_INTERVAL, function () {

$this->check();

});

}

private function check()

{

$client = new Client('127.0.0.1', 9501);

$ret = $client->upgrade('/');

if (!$ret) {

// 连接异常时发送通知邮件

$errMsg = sprintf(

'websocket服务异常,错误状态码:%d,错误信息:%s,当前时间:%s',

$client->errCode,

socket_strerror($client->errCode),

$this->format());

echo $errMsg . PHP_EOL;

$this->sendEmail();

} else {

echo sprintf('服务正常,当前时间:%s', $this->format());

echo PHP_EOL;

$client->close();

}

}

private function sendEmail()

{

if ($this->table->exists('email')) {

$record = $this->table->get('email');

if ($this->now() - $record['send_time'] > self::EMAIL_INTERVAL) {

echo '发送邮件...' . PHP_EOL;

$this->table->set('email', ['send_time' => $this->now()]);

}

} else {

$this->table->set('email', ['send_time' => $this->now()]);

echo '发送邮件...' . PHP_EOL;

}

}

private function now()

{

return time();

}

private function format($timestamp = null)

{

if (is_null($timestamp)) {

$timestamp = $this->now();

}

return date('Y-m-d H:i:s', $timestamp);

}

}

$check = new CheckPos();

$check->schedule();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值