swoole socket 使用

<?php


//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);

//监听WebSocket连接打开事件
/**
 * 客户端想服务器发送信息是调用函数
 * $ws   websocket 服务器
 * $request 客户端信息
 * $request->fd 客户端唯一编号
 *
 * */
$ws->on('open', function ($ws, $request) {
    //var_dump($request->fd, $request->get, $request->server);
    //$ws->push($request->fd, "hello, welcome\n");
    echo "connection open:{$request->fd}\n";
    //$ws->push($request->fd, json_encode(['hello','world']));
});

//监听WebSocket消息事件
/**
 * $frame 客户端发送的信息
 * $frame->fd 客户端的唯一编号
 * $frame->data 客户端发送的信息
 * */
 
 $ws->on("request", function(swoole_http_request $request, swoole_http_response $response) use($ws){
 	
  
    //遍历所有WebSocket连接用户的fd,给所有用户推送
    global $ws;
    foreach ($ws->connections as $fd) {
        // 需要先判断是否是正确的websocket连接,否则有可能会push失败
        if ($ws->isEstablished($fd)) {
            $ws->push($fd, $request->post['scene']);
        }
    }
});
 
 
 
$ws->on('message', function ($ws, $frame) {
    //echo "接收到的信息: {$frame->data}\n";
    //$ws->push($frame->fd, "server: {$frame->data}");
    //echo "服务器已接收:【".$frame->fd."】";
    //$ws->push($frame->fd, json_encode(['hello','world'.$frame->data]));


    // 1.客户端发送过来的信息
    $content = $frame->data;
    echo "服务器接收到信息:".$content;
    // 2.讲消息发送个所有客户端
    foreach ($ws->connections as $fd){

	   $content = "你好";
    	
        $ws->push($fd,$content);
    }
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
    echo "已断开链接:{$fd}";
});

$ws->start();






?>
  function curl($data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "http://127.0.0.1:9502");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_exec($curl);
        curl_close($curl);
    }


    function activepush()
    {
        $param['scene'] = '主动推送消息';
        curl($param);   // 主动推送消息
    }

 

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容