前戏:实现用户下单,服务器通知后台接收订单...类似美团外卖
1.首先要实现一个订阅程序
$result = $client->connect('127.0.0.1', 6379, function (swoole_redis $client, $result) {
$client->subscribe('order'); //实现订阅order
});
2.客户下单会产生一个publish推送到订阅order中
3.websocket推送
$client->on('message', function (swoole_redis $client, $result) use ($server,$request) {
if ($result[0] == 'message'){
$server->push($request->fd, $result[2]);
}
});
完整代码
<?php
$server = new swoole_websocket_server("0.0.0.0", 9533);
$server->on('open', function ($server, $request) {
$client = new swoole_redis;
$client->on('message', function (swoole_redis $client, $result) use ($server,$request) {
if ($result[0] == 'message'){
$server->push($request->fd, $result[2]);
}
});
$result = $client->connect('127.0.0.1', 6379, function (swoole_redis $client, $result) {
$client->subscribe('order'); //实现订阅order
});
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
$server->push($frame->fd, "areyouok");
});
$server->on('close', function ($serv, $fd) {
//处理关闭
});
$server->start();