Laravel + Swoole 打造IM簡(jiǎn)易聊天室
最近在學(xué)習(xí)Swoole,利用Swoole擴(kuò)展讓PHP生動(dòng)了不少,本篇就來(lái)Swoole開發(fā)一款簡(jiǎn)易的IM聊天室
應(yīng)用場(chǎng)景:實(shí)現(xiàn)簡(jiǎn)單的即時(shí)消息聊天室.
(一)擴(kuò)展安裝
pecl install swoole
安裝完成后可以通過以下命令檢測(cè)Swoole是否安裝成功
php -m | grep swoole
(二)webSocket服務(wù)端代碼
我們需要通過Laravel Command來(lái)實(shí)現(xiàn),因?yàn)镾woole只能運(yùn)行在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()
{
//創(chuàng)建server
$server = new \Swoole\WebSocket\Server("0.0.0.0", 9502);
//連接成功回調(diào)
$server->on('open', function (\Swoole\WebSocket\Server $server, $request) {
$this->info($request->fd . '鏈接成功');
});
//收到消息回調(diào)
$server->on('message', function (\Swoole\WebSocket\Server $server, $frame) {
$content = $frame->data;
//推送給所有鏈接
foreach ($server->connections as $fd){
$server->push($fd,$content);
}
});
//關(guān)閉鏈接回調(diào)
$server->on('close', function ($ser, $fd) {
$this->info($fd . '斷開鏈接');
});
$server->start();
}
}
3.運(yùn)行服務(wù)端
php artisan swoole:server
(三)客戶端實(shí)現(xiàn)
1.HTML+JS代碼實(shí)現(xiàn)
<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="請(qǐng)輸入內(nèi)容">
<button type="button" class="btn btn-primary" onclick="sendMessage()">Primary</button>
</div>
</div>
<script type="text/javascript">
if(window.WebSocket){
// 端口和ip地址對(duì)應(yīng)不要寫錯(cuò)
var webSocket = new WebSocket("ws://127.0.0.1:9502");
webSocket.onopen = function (event) {
console.log('webSocket 鏈接成功');
};
//收到服務(wù)端消息回調(diào)
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>
通過以上的代碼便完善一個(gè)基本的簡(jiǎn)易聊天室,但是距離一個(gè)真正完善的及時(shí)通訊系統(tǒng)構(gòu)建還相差甚遠(yuǎn),具體的理解和應(yīng)用都寫在了代碼注釋中,如有不能理解的地方,可以去查看Swoole官方文檔以及Webscoket Api.
附上聊天室演示圖:

聊天室演示