Laravel + Swoole 打造IM簡易聊天室


最近在學習Swoole,利用Swoole擴展讓PHP生動了不少,本篇就來Swoole開發一款簡易的IM聊天室

應用場景:實現簡單的即時消息聊天室.

(一)擴展安裝

pecl install swoole

安裝完成后可以通過以下命令檢測Swoole是否安裝成功

php -m | grep swoole

(二)webSocket服務端代碼

我們需要通過Laravel Command來實現,因為Swoole只能運行在PHP CLI模式下.

1.生成Command類

php artisan make:command SwooleServer

2.編寫webSocket Server邏輯

<?php namespace App\Console\Commands; use Illuminate\Console\Command; class SwooleServer extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'swoole:server'; /** * The console command description. * * @var string */ protected $description = 'swoole websocket'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { //創建server $server = new \Swoole\WebSocket\Server("0.0.0.0", 9502); //連接成功回調 $server->on('open', function (\Swoole\WebSocket\Server $server, $request) { $this->info($request->fd . '鏈接成功'); }); //收到消息回調 $server->on('message', function (\Swoole\WebSocket\Server $server, $frame) { $content = $frame->data; //推送給所有鏈接 foreach ($server->connections as $fd){ $server->push($fd,$content); } }); //關閉鏈接回調 $server->on('close', function ($ser, $fd) { $this->info($fd . '斷開鏈接'); }); $server->start(); } } 

3.運行服務端

php artisan swoole:server 

(三)客戶端實現

1.HTML+JS代碼實現

<div style="width:600px;margin:0 auto;border:1px solid #ccc;"> <div id="content" style="overflow-y:auto;height:300px;"></div> <hr /> <div style="height:40px;background:white;"> <input type="text" class="form-control" id="message" placeholder="請輸入內容"> <button type="button" class="btn btn-primary" onclick="sendMessage()">Primary</button> </div> </div> <script type="text/javascript"> if(window.WebSocket){ // 端口和ip地址對應不要寫錯 var webSocket = new WebSocket("ws://127.0.0.1:9502"); webSocket.onopen = function (event) { console.log('webSocket 鏈接成功'); }; //收到服務端消息回調 webSocket.onmessage = function (event) { var content = document.getElementById('content'); content.innerHTML = content.innerHTML.concat('<p style="margin-left:20px;height:20px;line-height:20px;">'+event.data+'</p>'); } var sendMessage = function(){ var data = document.getElementById('message').value; webSocket.send(data); } }else{ console.log("您的瀏覽器不支持WebSocket"); } </script> 

通過以上的代碼便完善一個基本的簡易聊天室,但是距離一個真正完善的及時通訊系統構建還相差甚遠,具體的理解和應用都寫在了代碼注釋中,如有不能理解的地方,可以去查看Swoole官方文檔以及Webscoket Api.



作者:理想啊
鏈接:https://www.jianshu.com/p/b5ee9f72fcd1
來源:簡書


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM