<?php
class Ws{
const HOST = '0.0.0.0'; // 監聽的IP位址, 0.0.0.0 表示監聽所有IP位址
const PROT = '9504';
public $ws = null; // 存放websocket連接配接資源
public $config = [
// 程序數
'worker_num' => 2,
];
public function __construct()
{
// 建立 websocket server對象
$this->ws = new swoole\websocket\server(self::HOST, self::PROT);
// 設定參數
$this->ws->set($this->config);
// 監聽websocket連接配接事件
$this->ws->on('open', [$this, 'onOpen']);
// 監聽websocket消息事件
$this->ws->on('message', [$this, 'onMessage']);
// 監聽websocket連接配接關閉事件
$this->ws->on('close', [$this, 'onClose']);
// 啟動服務
$this->ws->start();
}
/**
* 監聽websocket連接配接事件
* @param $ws
* @param $request
*/
public function onOpen($ws, $request)
{
var_dump($request->fd);
}
/**
* 監聽websocket消息事件
* @param $ws
* @param $frame
*/
public function onMessage($ws, $frame)
{
/**
* 設定一個間隔時間定時器 每2秒執行
* 回調函數參數 $timer_id 定時器的 ID 清除時使用
* 回調函數參數 $params.... ,對應 tick 的第三個及之後傳入的參數
*/
$timer = swoole_timer_tick(2000, function($timer_id, $param1, $param2) {
echo '2s,定時器id: '. $timer_id. PHP_EOL;
echo $param1. ' - '. $param2. PHP_EOL; // 第一個參數, 第二個參數
}, '第一個參數', '第二個參數');
// 在指定的時間後執行函數 一次性定時器,執行完成後就會銷毀
swoole_timer_after(5000, function() use($ws, $frame, $timer) {
echo '5s after 關閉定時器'. PHP_EOL;
// 5s後向用戶端發送一條消息
$ws->push($frame->fd, '我是5s的一次性事件');
// 清除定時器 參數為定時器id
swoole_timer_clear($timer);
// 清除目前 Worker 程序内的所有定時器 需要 Swoole 版本 >= v4.4.0
swoole_timer_clearAll();
});
}
/**
* 監聽websocket連接配接關閉事件
* @param $ws
* @param $fd
*/
public function onClose($ws, $fd)
{
echo '退出了:'. $fd. PHP_EOL;
}
}
new Ws();