swoole中websoket创建在线聊天室(php)
swoole现仅支持Linix,macos
创建websocket服务器
首先现在服务器创建一个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页面
创建一个简单可用的swoole聊天室
<!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>
标签:websoket,聊天室,swoole,server,json,ws,php,data From: https://www.cnblogs.com/gaoyusui/p/16986615.html