雅安论坛

标题: SWOOLE相关知识 [打印本页]

作者: 未命名    时间: 2021-12-31 12:02
标题: SWOOLE相关知识
  1. <?php
  2. //创建websocket服务器对象,监听0.0.0.0:9502端口
  3. $ws = new swoole_websocket_server("0.0.0.0", 9501);

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

  18. //监听WebSocket消息事件
  19. /**
  20. * $frame 客户端发送的信息
  21. * $frame->fd 客户端的唯一编号
  22. * $frame->data 客户端发送的信息
  23. * */
  24. $ws->on('message', function ($ws, $frame) {
  25.     //echo "接收到的信息: {$frame->data}\n";
  26.     //$ws->push($frame->fd, "server: {$frame->data}");
  27.     //echo "服务器已接收:【".$frame->fd."】";
  28.     //$ws->push($frame->fd, json_encode(['hello','world'.$frame->data]));


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

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

  42. 显示数据:
复制代码
来源:https://www.cnblogs.com/wesky/p/9449647.html






欢迎光临 雅安论坛 (https://www.yaanbbs.net/) Powered by Discuz! X3.4