swoole

服務(wù)端

/**

  • 服務(wù)

  • Class Server
    /
    class Server
    {
    /
    *

    • swoole服務(wù)
    • @var
      */
      private $serv;

    /**

    • redis服務(wù)
    • @var
      */
      private $redis;

    /**

    • 服務(wù)啟動
      */
      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,// 是否開啟守護(hù)進(jìn)程
      ));
      //監(jiān)聽WebSocket連接打開事件
      $this->serv->on('open', [$this, 'onOpen']);
      //監(jiān)聽WebSocket消息事件
      $this->serv->on('message', [$this, 'onMessage']);
      $this->serv->on('worker', [$this, 'onWorker']);

      //監(jiān)聽WebSocket連接關(guān)閉事件
      $this->serv->on('close', [$this, 'onClose']);

      //監(jiān)聽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";
      }

    /**

    • /**
    • 監(jiān)聽WebSocket連接打開事件
      */
      public function onOpen($ws, $request)
      {
      echo 'onOpen';
      }

    /**

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

    /**

    • 監(jiān)聽WebSocket連接關(guān)閉事件
      */
      public function onClose($ws, $fd)
      {
      echo 'onClose';
      }

}

// 啟動服務(wù)器
$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("連接已關(guān)閉...");
};
}
else {
console.log("您的瀏覽器不支持 WebSocket!");
}
</script>
</head>
<body>
<h1 id="haha"></h1>
</body>
</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容