合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
``` <?php //创建WebSocket Server对象,监听0.0.0.0:9502端口 $ws = new Swoole\WebSocket\Server('0.0.0.0', 9503); //监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request) { $fd=$request->fd; var_dump($request->fd, $request->server); $ws->push($request->fd, "hello, welcome\n"); }); //监听WebSocket消息事件 $ws->on('message', function ($ws, $frame) { //echo "Message: {$frame->data}\n"; $ws->push($frame->fd, "服务端返回:{$frame->data}"); }); //第一种方式:通过curl调用swoole.xian008.com:9501(客户端websocket连接地址) $ws->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) { global $ws;//调用外部的server //$server->connections 遍历所有websocket连接用户的fd,给所有用户推送 foreach ($ws->connections as $fd) { // 需要先判断是否是正确的websocket连接,否则有可能会push失败 if ($ws->isEstablished($fd)) { $ws->push($fd, $request->post['message']); } } }); 第二种方式:通过redis订阅来实现 $process = new Swoole\Process(function ($process)use($ws) { echo 'process'; $redis = new \Redis(); $redis->connect('127.0.0.1',6379); $redis->auth('xiaocinao'); $redis->subscribe(['name'],function ($redis,$channel,$msg)use($ws){ $ws->push(1,$msg); }); }); //监听WebSocket连接关闭事件 $ws->on('close', function ($ws, $fd) { echo "client-{$fd} is closed\n"; }); $ws->addProcess($process); $ws->start(); ```