laravel5.4實(shí)現(xiàn)實(shí)時(shí)聊天室

一、修改laravel的廣播驅(qū)動

修改 .env中:

BROADCAST_DRIVER=redis

二、創(chuàng)建laravel事件廣播

比如要創(chuàng)建一個(gè)發(fā)送聊天消息的事件,則

php artisan make:event SendChat

后在app/events里面會有SendChat.php

SendChat.php:

//由于該事件需要廣播,則該類需要實(shí)現(xiàn)ShouldBroadcast

Class SendChat implements ShouldBroadcast {

    //然后將需要廣播的數(shù)據(jù)以public形式寫在此類作為成員屬性
    public $input;

    //new對象時(shí)存入的數(shù)據(jù)
    public function __construct($input)  {      
        $this->input = $input;  
    }

    public function broadcastOn()  {
        //公共channel      
        return ['test-channel']; 
    }

}

最后將會得到如下數(shù)據(jù):

頻道:test-channel

數(shù)據(jù):{"event":"App\Events\UserSignUp","data":{"input":"xulibin","socket":null},"socket":null}

Redis版本:
若不用laravel 的broadcast,則可以用Redis(它也有發(fā)布和訂閱功能)

$data = ['event' => 'SendChat','data'  => ['input' => 'xlb'] ];

Redis::publish('test-channel',json_encode($data));

最后將會得到如下數(shù)據(jù):

頻道:test-channel

數(shù)據(jù):{"event":"SendChat","data":{"input":"xlb"}}

三、創(chuàng)建node服務(wù)器,接受laravel事件廣播,再轉(zhuǎn)廣播給前端client,此處Node服務(wù)器是占用了3000端口,待會client也要監(jiān)聽這個(gè)3000端口。

1、另外還需要引入socket.io和ioredis

npm install socket.io ioredis --save

2、創(chuàng)建socket.js(這次是創(chuàng)建在項(xiàng)目根目錄,也可其他目錄)

var server = require('http').Server();
var io = require('socket.io')(server);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('test-channel');
redis.on('message',function(channel,message){
    message = JSON.parse(message);
    console.log(channel+':'+message.event);
    //這里是以“頻道:事件”的方式去發(fā)送,需要接受此事件的client就接受此格式的事件
    //test-channel:SendChat
    io.emit(channel+':'+message.event,message.data);  
});

server.listen(3000);

然后一定要開啟node服務(wù)器

node socket.js //(如果js位置不同,也要加上前面的目錄)

四、Client
引入vue.js(非必要),socket.is.js,vue-resource(非必要)

<script src="https://cdn.bootcss.com/vue/2.3.4/vue.js"></script> 
<script src="https://cdn.bootcss.com/socket.io/2.0.3/socket.io.js"></script>  
<script src="https://cdn.bootcss.com/vue-resource/1.3.4/vue-resource.min.js"></script>
<div id="container">
    <h1>New Users:</h1>
    <ul>
        <li v-for="chat in chatList">@{{chat}}</li>
    </ul>
    <div>
        <input type="text" v-model="chatInput"/>
        <button @click="submit">提交</button>
    </div>
</div>
<script>
    //監(jiān)聽服務(wù)器的3000端口
    var socket = io('http://192.168.10.10:3000');
    new Vue({
        el:'#container',

        data:{
            users:[],
            chatInput:'',
            submitUrl: 'http://localhost:8000/api/submit'  ,
            chatList:[]
        },

        mounted:function(){
            //socket.on('test-channel:UserSignUp',function(data){
            socket.on('test-channel:App\\Events\\UserSignUp',function(data){
                console.log(data);
                this.chatList.push(data.input);
            }.bind(this));
        },
        methods:{
            submit(){
                var that = this;
                that.$http.post(
                    this.submitUrl,
                    {'input':this.chatInput}
                ).then(function(response){  //接口返回?cái)?shù)據(jù)
                },function(error){
                })
            }
        }

    });
</script>

然后該按鈕提交后,服務(wù)端的代碼如下

$input = $request->input('input');
//觸發(fā)發(fā)送聊天信息事件
event(new SendChat($input));
return $input;

五、流程圖

圖片1.png

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

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

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,545評論 19 139
  • 一觸記憶,多少關(guān)愛我,呵護(hù)我的片段激勵著我成長,經(jīng)歷我上進(jìn),使我走向成功的道路。似一抹陽光射入我冰封的心田...
    張清姝閱讀 410評論 0 1
  • 【幼兒說】原創(chuàng),轉(zhuǎn)載請標(biāo)出處 兒童“性”安全干貨。 包括:兒童“性”安全中,70%以上的傷害是某類人所為;幼兒遭遇...
    幼兒說閱讀 436評論 0 1
  • 事件 上周去深圳出差,本次的任務(wù)主要是客戶買我公司的設(shè)備出現(xiàn)故障,需要去現(xiàn)場解決故障的! 到達(dá)現(xiàn)場后,通過對故障原...
    放平自我閱讀 178評論 0 0
  • 為什么至今楚門還不知道自己活在一個(gè)什么樣的世界?回答:因?yàn)槲覀兌冀邮墁F(xiàn)實(shí)。 “農(nóng)村原來沒有跑道,后來學(xué)校里有了跑道...
    星辰一點(diǎn)閱讀 666評論 0 3

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