Laravel + Swoole 打造IM簡易聊天室

Laravel + Swoole 打造IM簡易聊天室

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

應(yīng)用場景:實現(xiàn)簡單的即時消息聊天室.

(一)擴展安裝

pecl install swoole

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

php -m | grep swoole

(二)webSocket服務(wù)端代碼

我們需要通過Laravel Command來實現(xiàn),因為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()
    {
        //創(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.運行服務(wù)端

php artisan swoole:server

(三)客戶端實現(xiàn)

1.HTML+JS代碼實現(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="請輸入內(nèi)容">
        <button type="button" class="btn btn-primary" onclick="sendMessage()">Primary</button>
    </div>
</div>

<script type="text/javascript">
    if(window.WebSocket){
          // 端口和ip地址對應(yīng)不要寫錯
          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>

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

附上聊天室演示圖:


聊天室演示
最后編輯于
?著作權(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)容