~~~
<?php
namespace server;
use Swoole\Coroutine\Redis;
use Swoole\WebSocket\Server;
class WebSocketServer
{
protected $server = null; //示例server對象
protected $host = "0.0.0.0"; //監聽對應外網的IP
protected $port = 9504; //監聽端口
public function __construct()
{
//實例化swoole服務
$this->server = new Server($this->host, $this->port);//第三個參數默認是TCP,可不填
//監聽多端口
$http = $this->server->listen($this->host, 9999, SWOOLE_SOCK_TCP);
$http->on("request", [$this, 'onRequest']);
//設置參數 worker_num:全異步IO的,CPU核數的1~4倍;同步IO的,需要根據請求響應時間和系統負載來調整,例如:100-500
$this->server->set([
"worker_num" => 4, //設置啟動的worker進程數 【默認是CPU的核數】
"max_request" => 10000, //設置每個worker進程的最大任務數 【默認值:0 即不會退出進程】
"daemonize" => 0, //守護進程化【默認值:0】
]);
//監聽連接打開事件
$this->server->on("open", [$this, 'onOpen']);
//$this->server->on("request", [$this, 'onRequest']);
//監聽WebSocket消息事件
$this->server->on("message", [$this, 'onMessage']);
//監聽客戶端連接關閉事件
$this->server->on("close", [$this, 'onClose']);
$this->server->start();
}
public function onOpen($ws, $request) {
echo "connestion open : {$request->fd}".PHP_EOL;
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$data = $redis->lRange("dy", 0, -1);
if ($data) {
foreach ($ws->connections as $fd) {
$ws->push($fd, json_encode($data));
}
}
}
public function onRequest($request, $response) {
$data = $request->post;
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
if ($data) {
foreach ($data as $v) {
$redis->lPush("dy", $v);
}
}
}
//付款之后,通知所有人我已經買了這些票了
public function onMessage($ws, $frame) {
if ($frame->data == "success") {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$data = $redis->lRange("dy", 0, -1);
foreach ($ws->connections as $fd) {
$ws->push($fd, json_encode($data));
}
}
}
public function onClose($ws, $fd) {
echo "客戶端關閉:{$fd}".PHP_EOL;
}
}
$webSocketServer = new WebSocketServer();
~~~