swoole中websoket建立線上聊天室(php)
阿新 • • 發佈:2021-01-07
swoole中websoket建立線上聊天室(php)
建立websocket伺服器
<?php //建立websocket伺服器 $server = new Swoole\WebSocket\Server("0.0.0.0", 6060); // 當WebSocket客戶端與伺服器建立連線並完成握手後會回撥此函式 $server->on('open', function (Swoole\WebSocket\Server $server, Swoole\Http\Request $request) { }); // 伺服器主動向客戶端傳送資料 $server->on('message', function (Swoole\WebSocket\Server $server, swoole_websocket_frame $frame) { $data = $frame->data; $ret['data'] = $data; //廣播群發 foreach ($server->connections as $client) { //判斷客戶端是否自己 if ($frame->fd == $client) { $ret['style'] = 'bubble me'; } else { $ret['style'] = 'bubble you'; } @$server->push($client, json_encode($ret, 256)); } }); // 客戶端關閉連線時觸發此回撥函式 $server->on('close', function ($ser, $fd) { }); // 啟動服務 $server->start();
html頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>線上聊天室</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/reset.min.css"> <link rel="stylesheet" href="css/style.css"> </head> <body> <div class="wrapper"> <div class="container"> <div class="left"> <div class="top"> 線上人員</div> <ul class="people"> <li class="person" data-chat="person1"> <img src="img/thomas.jpg" alt=""/> <span class="name">張三</span> <span class="time">10:09</span> </li> <li class="person" data-chat="person2"> <img src="img/dog.png" alt=""/> <span class="name">李四</span> <span class="time">10:44</span> </li> <li class="person" data-chat="person3"> <img src="img/louis-ck.jpeg" alt=""/> <span class="name">王五</span> <span class="time">10:50</span> </li> </ul> </div> <div class="right"> <div class="top"><span><span class="name">聊天室</span></span></div> <div class="chat" data-chat="person2"> <template v-for="item in msglist"> <div :class="item.style"> {{ item.data }} </div> </template> </div> <div class="write"> <input type="text" v-model="msg" placeholder="輸入內容" @keydown.enter="send"/> <!-- vue 修飾符 once prevent stop enter shift alt --> <a @click.prevent="send" class="write-link send"></a> </div> </div> </div> </div> <script src="js/index.js"></script> <script src="js/vue.js"></script> <script> // 客戶端連線websocket伺服器端 const ws = new WebSocket('ws://175.24.114.149:6060'); // 事件監聽 // 建議時事件 ws.onopen = () => { console.log('連線建立') }; // 接受訊息事件 ws.onmessage = ({data}) => { // 返回的是一個json字串,json字串轉為物件 es6提供一個方法 let json = JSON.parse(data); // 使用vue提供變異方法 vm.msglist.push(json); }; // 例項化 主元件中,data是用的物件非函式 子元件data用的是函式返回一個物件 const vm = new Vue({ el: '.wrapper', data: { msg: '', // 訊息列表 msglist: [] }, methods: { // 傳送訊息事件 send() { ws.send(this.msg); this.msg = ''; } } }); </script> </body> </html>