首页 > 编程语言 >【php】swoole中websoket创建在线聊天室

【php】swoole中websoket创建在线聊天室

时间:2022-12-21 14:22:05浏览次数:57  
标签:websoket 聊天室 swoole server json ws php data

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

相关文章

  • Thinkphp3.2.3 SQL注入总结
    下载:ThinkPHP3.2.3完整版-ThinkPHP框架配置ThinkPHP/Conf/convention.php配置下数据库,我这里直接用的sqllabs的数据库写个查询入口Application/Home/Controller/Ind......
  • PHP Web System Optimization(undone)
    PHPOptimization目录0.引言1.PHPPool2.listen3.ProcessManage(PM)4.pm.max_children5.PHPDBConnectionPool(数据库连接池) 0.引言0x1......
  • php使用curl时 file_exists(): Unable to find the wrappe
    php使用curl时报错:file_exists():Unabletofindthewrappe解决办法,打开php.ini文件,找到下面代码:1.extension=php_openssl.dll把前面的注释去掉2.allow_url_include......
  • php命令行选项
    命令行选项选项名称长名称说明-a--interactive交互式运行PHP。如果编译PHP时加入了​​Readline​​扩展(Windows下不可用),那将会得到一个很好的外壳,包括一个自动......
  • PHP 8 安装amqp扩展
    php8安装amqp扩展1.安装rabbitmq-c#下载源码wgethttps://github.com/alanxz/rabbitmq-c/archive/refs/tags/v0.11.0.tar.gz#解压tar-zxvfv0.11.0.tar.gz#进人目录......
  • PHP无锁内存nosql---Yac的实战
    无锁内存nosql---Yac的实战最近在工作使用了yac,所以比较了下Memcache和Yac的高并发读写性能测试,发现Yac要比Memcache快很多(这里没有比较Yac和Apc的性能情况,不过......
  • 搭建LAMP并使用mysql的phpMyadmin图形化管理工具
    #1.环境为centos7系统#2.安装httpd服务yum-yinstallhttp#安装HTTP服务systemctlstarthttpd#启动HTTP服务systemctlenablehttpd#开机启动HTTP服务firewall-c......
  • thinkphp6 订阅
    event.php<?php//事件定义文件return['bind'=>['UserLogin'=>'app\event\UserLogin','UserLogout'=>'app\event\UserLogin',......
  • PHP 8 Apache 2.4
    PHP8一、下载官网:PHPForWindows:BinariesandsourcesReleases切记要下载ThreadSafe版本,不然后面不能够连接Apache服务  二、安装 1、将该文件解压到(D:\PH......
  • php 滑动图片验证生成
    1.话不多说,直接干货,喜欢的希望大家一键三连<?phpnamespaceApp\Model;classVerifyImage{//浮层坐标数组protected$tailoringArray=[];//浮层......