Swoole是一個使用C語言寫出來的PHP extension,本篇筆記了如何使用Laravel+Swoole來打造websocket應用,包含從伺服器安裝到基本範例程式,有websocket基本觀念後,再花點時間,就能把程式改成多人聊天室或私頻聊天等應用了。
- 由於Swoole不支援Windows,以下操作皆是在linux(Ubuntu 22.04)系統環境下運作的。
Requirement
需先確認系統有安裝PHP與Nginx,本文是在此基礎環境下運作的。
$ sudo apt update
$ sudo apt upgrade
$ sudo apt install nginx
$ sudo apt install php8.1-fpm php8.1 php-dev -y
$ php -v
安裝PHP swoole擴展
$ sudo pecl install swoole
$ sudo apt install php-pear
enable swoole:
- 打開php.ini:
$ sudo nano /etc/php/8.1/cli/php.ini
$ php --ini
2. 在php.ini 檔案最後面加上:
extension=swoole.so
3. Restart php-fpm生效:
$ sudo service php8.1-fpm restart
查看swoole是否安裝成功:
$ php -m
安裝composer
$ sudo apt install curl unzip
$ sudo apt install php-curl
$ curl -sS https://getcomposer.org/installer -o composer-setup.php
$ sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
$ composer -V
安裝Laravel Installer
- 使用Composer安裝Laravel Installer:
$ composer global require "laravel/installer"
- 將 composer bin folder 加入環境變數,這樣才能用laravel指令來建立專案:
$ nano $HOME/.bashrc
$ export PATH="$PATH:$HOME/.config/composer/vendor/bin"
$ source $HOME/.bashrc
建立Laravel新專案
- 接著就能用laravel installer來建立Laravel新專案:
$ laravel new swoole_test
安裝laravel-swoole
- 接著在swoole_test專案目錄下,安裝laraveltw/laravel-swoole:
$ composer require swooletw/laravel-swoole
撰寫Swoole websocket後端程式
$ php artisan make:command Swoole
會在app\Console\Command路徑下建立Swoole.php:
將code改成這樣:
撰寫Swoole websocket前端程式
啟動websocket server
$ php artisan swoole start
接著當client連線時,瀏覽器與server訊息如下圖:
本筆記參考:
- https://www.jianshu.com/p/b5ee9f72fcd1
- https://learnku.com/articles/4633/with-supervisor-use-swoole-to-create-a-websocket-server-in-laravel
- https://learnku.com/articles/47250
- https://iter01.com/520130.html
- https://www.swoole.com/
- https://blog.albert-chen.com/php-with-swoole/
- https://www.cloudbooklet.com/how-to-install-lemp-stack-nginx-mysql-php-on-ubuntu-22-04/
- https://www.how2shout.com/linux/how-to-install-composer-on-ubuntu-22-04-20-04-lts/
- https://stackoverflow.com/questions/61395786/i-get-laravel-command-not-found-on-ubuntu-20-04
- https://wiki.swoole.com/#/environment