swoole

服务端

/**

  • 服务

  • Class Server
    /
    class Server
    {
    /
    *

    • swoole服务
    • @var
      */
      private $serv;

    /**

    • redis服务
    • @var
      */
      private $redis;

    /**

    • 服务启动
      */
      public function index()
      {
      $this->serv = new swoole_websocket_server($this->config['SWOOLE_URL'], $this->config['SWOOLE_PORT']);
      $this->serv->set(array(
      'worker_num' => 4,
      'daemonize' => true,// 是否开启守护进程
      ));
      //监听WebSocket连接打开事件
      $this->serv->on('open', [$this, 'onOpen']);
      //监听WebSocket消息事件
      $this->serv->on('message', [$this, 'onMessage']);
      $this->serv->on('worker', [$this, 'onWorker']);

      //监听WebSocket连接关闭事件
      $this->serv->on('close', [$this, 'onClose']);

      //监听WebSocket连接启动事件
      $this->serv->on('start', [$this, 'onStart']);

      $this->serv->start();
      }

    public function onWorker($ws, $worker_id)
    {
    swoole_timer_tick(2000, function ($timer_id) use ($ws, $worker_id) {
    });
    }

    /**

    • 记录开启日志
      */
      public function onStart($ws)
      {
      echo "onStart";
      }

    /**

    • /**
    • 监听WebSocket连接打开事件
      */
      public function onOpen($ws, $request)
      {
      echo 'onOpen';
      }

    /**

    • 监听WebSocket消息事件
      */
      public function onMessage($ws, $frame)
      {
      $ws->push($frame->fd, json_encode([
      'result' => [
      'serverTime' => $frame->data
      ]
      ]));
      }

    /**

    • 监听WebSocket连接关闭事件
      */
      public function onClose($ws, $fd)
      {
      echo 'onClose';
      }

}

// 启动服务器
$server = new Server();
$server->index();

客户端





Title





你可能感兴趣的:(swoole)