swoole 簡(jiǎn)單聊天室

最開始想laravel+swoole打造一個(gè)簡(jiǎn)單的聊天室
然后開啟server時(shí)候發(fā)現(xiàn)沒必要,在哪寫都一樣
所以我另外在laravel外面寫了個(gè)server的目錄,用作簡(jiǎn)單調(diào)試


image.png

以下是代碼塊
swooleServer.php

<?php

class swooleServer
{
    public $server;
    public function __construct()
    {
        $this->server = new \Swoole\WebSocket\Server("0.0.0.0", 9501);
    }

    public function go()
    {

        // 客戶端鏈接時(shí)候觸發(fā)
        $this->server->on('open', function (Swoole\WebSocket\Server $server, $request) {
            echo "server: handshake success with fd{$request->fd}\n";
        });
        // 客戶端發(fā)送消息的時(shí)候觸發(fā)
        $this->server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
            echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
//            $server->push($frame->fd, "{$frame->data}");
            // 獲取到里面所有的鏈接id,然后逐個(gè)廣播
            foreach ($this->server->connections as $fd) {
                // 需要先判斷是否是正確的websocket連接,否則有可能會(huì)push失敗
                if ($this->server->isEstablished($fd)) {
                    // push到server 然后客戶端接收
                    $this->server->push($fd, json_encode(['on'=>$frame->fd,'msg'=>$frame->data]));
                }
            }
        });
        // 客戶端關(guān)閉鏈接的時(shí)候觸發(fā)
        $this->server->on('close', function ($ser, $fd) {
            echo "client {$fd} closed\n";
        });

        // 運(yùn)行server
        $this->server->start();
    }
}

$ser = new swooleServer();
$ser->go();

用戶1的view。user/profile.blade.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div>
    用戶1:
</div>
<div>
    <div>

    </div>
    <div>
        <div>展示內(nèi)容</div>
        <div class="show_conten"></div>
    </div>
</div>
<div>
    <input type="text" name="text_val" value="" class="val">
    <button class="btn">提交</button>
</div>
</body>
</html>
<script type="text/javascript" src="{{URL::asset('js/jquery-1.8.3.min.js')}}"></script>
<script type="text/javascript">

    var wsUrl = "ws://laravelim.net:9501";
    var websocket = new WebSocket(wsUrl);

    $(function () {
        $('.btn').click(function () {
            var val = $('.val').val();
            if(val.length < 1) {
                return false;
            }
            websocket.send(val);
            $('.val').val('');

        });
        // 實(shí)例對(duì)象 onopen
        websocket.onopen = function(evt) {
            console.log('contected-success');
        };

        // onmessage
        websocket.onmessage = function(evt) {
            console.log('return_data',evt);
            var data1 = evt.data;
            var data = $.parseJSON(data1);
            var html = '<p>用戶'+ data.on +':'+ data.msg +'</p>';
            $('.show_conten').append(html);
        };

        // onclose
        websocket.onclose = function(evt) {
            console.log('關(guān)閉');
        }

        // onerror
        websocket.onerror = function(evt) {
            console.log('error',evt);
        }
    })

</script>

用戶2的view,home/profile.blade.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div>
    用戶2:
</div>
<div>
    <div>

    </div>
    <div>
        <div>展示內(nèi)容</div>
        <div class="show_conten"></div>
    </div>
</div>
<div>
    <input type="text" name="text_val" value="" class="val">
    <button class="btn">提交</button>
</div>
</body>
</html>
<script type="text/javascript" src="{{URL::asset('js/jquery-1.8.3.min.js')}}"></script>
<script type="text/javascript">

    var wsUrl = "ws://laravelim.net:9501";
    var websocket = new WebSocket(wsUrl);


    $(function () {
        $('.btn').click(function () {
            var val = $('.val').val();
            if(val.length < 1) {
                return false;
            }
            websocket.send(val);
            $('.val').val('');

        });
        // 實(shí)例對(duì)象 onopen
        websocket.onopen = function(evt) {
            console.log('contected-success');
        };

        // onmessage
        websocket.onmessage = function(evt) {
            console.log('return_data',evt);
            var data1 = evt.data;
            var data = $.parseJSON(data1);
            var html = '<p>用戶'+ data.on +':'+ data.msg +'</p>';
            $('.show_conten').append(html);
        };

        // onclose
        websocket.onclose = function(evt) {
            console.log('關(guān)閉');
        }

        // onerror
        websocket.onerror = function(evt) {
            console.log('error',evt);
        }
    })


</script>

最終效果


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

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

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