swoole

作者: 云边一片海 | 来源:发表于2018-05-31 11:39 被阅读0次

服务端

/**

  • 服务

  • 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();

客户端

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
if ("WebSocket" in window)
{
console.log("您的浏览器支持 WebSocket!");
var ws = new WebSocket("ws://192.168.1.158:9501");
ws.onConnect = function(){
ws.send("链接");
};
ws.onopen = function() {
ws.send("AService");
};
ws.onmessage = function(evt){
var received_msg = evt.data;
console.log(received_msg);
};
ws.onclose = function() {
console.log("连接已关闭...");
};
}
else {
console.log("您的浏览器不支持 WebSocket!");
}
</script>
</head>
<body>
<h1 id="haha"></h1>
</body>
</html>

相关文章

网友评论

    本文标题:swoole

    本文链接:https://www.haomeiwen.com/subject/hrhqsftx.html