## 一、业务代码
```
<?php
include "SwooleMySQL.php";
use frontend\controllers\SwooleMySQL;
use function Swoole\Coroutine\run;
//创建WebSocket Server对象,监听0.0.0.0:9502端口。
$ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);
//监听WebSocket连接打开事件。
$ws->on('Open', function ($ws, $request) {
$ws->push($request->fd, "websocket链接成功\n");
});
//监听WebSocket消息事件。
$ws->on('Message', function ($ws, $frame) {
$data = json_decode($frame->data, true);
if (!empty($data["user_id"]) && !empty($data["shop_id"]) && $data["middlebox_id"] ){
$userId = $data["user_id"];
$shopId = $data["shop_id"];
$boxId = $data["middlebox_id"];
$swooleMysqlClient = new SwooleMySQL();
$sql = "SELECT * FROM shop_items_middlebox_queue WHERE user_id = $userId AND shop_id = $shopId
AND middlebox_id = $boxId AND opened_at < time() AND closed_at > time()";
$shop = $swooleMysqlClient->query($sql);
if ($shop) {
$res =[
"code"=>200,
"msg"=>"排队时间已到,请您尽快前去抽盒"
];
$result = json_encode($res);
$ws->push($frame->fd,$result);
}
}
$ws->push($frame->fd,"ok");
});
//监听WebSocket连接关闭事件。
$ws->on('Close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
```
## 二、链接数据库
```
<?php
namespace frontend\controllers;
use Swoole;
class SwooleMySQL
{
private $pool;
public function __construct()
{
$this->pool = new Swoole\Coroutine\MySQL();
$this->pool->connect([
'host' => '101.200.179.32',
'port' => 3306,
'user' => 'mancool_test',
'password' => 'DGaJGyaG7ehisTx8',
'database' => 'mancool_test',
]);
}
public function query($sql)
{
return $this->pool->query($sql);
}
}
```
## 三、执行
```
php WebSocket.php
```
## 四、默认访问
默认访问 127.0.0.1:9502 (域名和端口填写自己的)
## 五、配置反向代理(nginx 反向代理 wss)
```
location /websocket {
# WebSocket代理配置
proxy_pass http://127.0.0.1:9502;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
# 如果你希望保留客户端的IP地址,可以传递以下头部
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 禁用缓存和缓冲,这对于WebSocket连接很重要
proxy_buffering off;
proxy_cache_bypass $http_upgrade;
# 设置超时时间
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
send_timeout 60s;
}
```
现在你的访问为:域名/websocket
## 六、其它操作
[链接 ](https://www.kancloud.cn/lengyueguang/linux/2027120)