网络异常,图片无法展示
|
一、效果图
网络异常,图片无法展示
|
二、前端页面
<!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.data.style"> {{ item.data.data }} </div> </template> <!-- <div class="bubble you">--> <!-- 帅哥好!--> <!-- </div>--> <!-- <div class="bubble me">--> <!-- 在的,美女!--> <!-- </div>--> </div> <div class="write"> <input type="text" v-model="msg" @keydown.enter="send()"/> <a href="javascript:;" class="write-link send" @click="send()"></a> </div> </div> </div> </div> </body> </html> <script src="js/index.js"></script> <script src="js/vue.js"></script> <script> //实例化对象 const ws = new WebSocket('ws://101.34.38.111:6060'); //监听建立连接事件 ws.onopen = () => { console.log('客户端建立了链接') } // 接收消息事件 //{} 叫解构赋值 对象的重命名解构 ws.onmessage = ({data}) => { // 返回的是一个json字符串,json字符串转为对象 es6提供一个方法 let json = JSON.parse(data) vm.msgList.push(json); console.log(vm.msgList) }; //进行实例化这个Vue const vm = new Vue({ el:'.wrapper', data:{ msg:'', msgList:[] }, //这个methods 必有加s methods:{ send(){ //获取输入框里面的值 let msg = this.msg //进行发送到websocket服务器 ws.send(msg) this.msg = '' } } }) </script> 复制代码
三、后台代码
<?php $server = new Swoole\WebSocket\Server("0.0.0.0", 6060); $server->on('open', function (Swoole\WebSocket\Server $server, $request) { //$server->push($request->fd, '欢迎进入我们的聊天室~'); }); //接收客户端发送的信息 //$frame 是 Swoole\WebSocket\Frame 对象,包含了客户端发来的数据帧信息 //$frame->fd 代表客户端的唯一标识 客户id //$frame->data 代表客户端发送的消息 $server->on('message', function (Swoole\WebSocket\Server $server, $frame) { //获取客户端发送的消息 $result['data'] = $frame->data; // $server->connections 遍历所有websocket连接用户的fd,给所有用户推送 foreach ($server->connections as $client) { //循环所有的客户端连接数据 //$client代表每一个用户的连接id //如果是同一个人 if ($client == $frame->fd) { $result['style'] = 'bubble me'; } else { $result['style'] = 'bubble you'; } $data = [ 'msg' => '操作成功', 'data' => $result, 'error_code' => 0 ]; //push推送给客户端信息 //进行广播,推送给所有用户 $server->push($client, json_encode($data, 256)); } }); $server->on('close', function ($ser, $fd) { echo "client {$fd} closed\n"; }); $server->start();