未命名 发表于 2021-12-31 12:02:56

SWOOLE相关知识

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

//监听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('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){
      $ws->push($fd,$content);
    }
});

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

显示数据:来源:https://www.cnblogs.com/wesky/p/9449647.html

页: [1]
查看完整版本: SWOOLE相关知识