阅读模式:

php swoole搭建简单的聊天室

查看:3692  回复:0  类型:  来源:php自学网  标签 html5 php swoole

        php使用swoole扩展搭建简单的在线实时聊天室,附带源码和界面预览。前端页面使用html5 websocket。

        预览地址:http://zixuephp.net/chat.html

一、websocket

    客户端完整源码查看:view-source:http://zixuephp.net/chat.html

    websocket客户端:

//client.html
$(function(){

    var wsname = $('.wsname1').text();
    var wsimg = $('.chatheadimg').attr('src');

    var wsServer = 'wss://zixuephp.net/ws';
    var websocket = new WebSocket(wsServer);
    websocket.onopen = function (event) {
        layer.msg('聊天室连接成功!');
        websocket.send('{"type":"1","name":"'+wsname+'","msg":"上线了!","self":"0","img":"'+wsimg+'"}');
    };

    websocket.onclose = function (event) {
        //console.log("连接关闭!");
        websocket.send('{"type":"3","name":"'+wsname+'","msg":"下线了!","self":"0","img":"'+wsimg+'"}');
    };

    websocket.onmessage = function (event) {
        //console.log(event.data);
        var chatmessage = JSON.parse(event.data);
        if(chatmessage){
            var ctype = chatmessage['type'];
            var cself = chatmessage['self'];
            var cname = chatmessage['name'];
            var ctime = chatmessage['time'];
            var cmsg = decodeURIComponent(chatmessage['msg']);
            var cimg = chatmessage['img'];
            var person = chatmessage['person'];
            if(ctype == 1){
                if( cself== 0){
                    layer.msg('【'+cname+'】'+cmsg);
                }
                $('.persion1').text(person);
            }else if (ctype == 2){
                var html ='';
                if( cself == 1){
                    html = "<div class=\"clearfix chatmessage\">\n" +
                        "                                    <div class=\"chatnametime rrn\">\n" +
                        "                                            <span>"+cname+"</span>&nbsp;&nbsp;\n" +
                        "                                            <span>"+ctime+"</span>\n" +
                        "                                    </div>\n" +
                        "                                    <div class=\"chatimgcon\">\n" +
                        "                                        <div class=\"fr\">\n" +
                        "                                            <img src=\""+cimg+"\" />" +
                        "                                        </div>\n" +
                        "                                        <div class=\"fr chcon\">"+cmsg+"</div>\n" +
                        "                                    </div>\n" +
                        "                                </div>";
                }else{
                    html = "<div class=\"clearfix chatmessage\">\n" +
                        "                                    <div class=\"chatnametime\">\n" +
                        "                                            <span>"+cname+"</span>&nbsp;&nbsp;\n" +
                        "                                            <span>"+ctime+"</span>\n" +
                        "                                    </div>\n" +
                        "                                    <div class=\"chatimgcon\">\n" +
                        "                                        <div class=\"fl\">\n" +
                        "                                            <img src=\""+cimg+"\" />\n" +
                        "                                        </div>\n" +
                        "                                        <div class=\"fl chcon\">"+cmsg+"</div>\n" +
                        "                                    </div>\n" +
                        "                                </div>";
                }

                $('.chatdetails').append(html);
                $('.persion1').text(person);
                $(".chatdetails").animate({scrollTop:$('.chatdetails')[0].scrollHeight},200);

            }else if(ctype == 3){
                $('.persion1').text(person);
                layer.msg('【'+cname+'】'+cmsg);
            }
        }
    };

    websocket.onerror = function (event, e) {
        layer.msg('聊天室错误'+event.data);
    };

    $(".chatsend").click(function(){
        var chatcon = '';
        chatcon = $('.chatcontent textarea').val();
        websocket.send('{"type":"2","name":"'+wsname+'","msg":"'+encodeURIComponent(chatcon)+'","self":"0","img":"'+wsimg+'"}');
        $('.chatcontent textarea').val(' ');
        $('.chatcontent textarea').focus();
    });

    window.onunload = function() {
        websocket.send('{"type":"3","name":"'+wsname+'","msg":"下线了!","self":"0","img":"'+wsimg+'"}');
    }
    
    //心跳
    setTimeout(function(){
        setInterval(function(){
            websocket.send('{"type":"4","name":"","self":"","img":"');
        },35000);
    },5000);
    
});

二、php swoole

    swoole服务端:

    需要安装php swoole扩展才能运行。编译安装的php如果没有swoole扩展的安装方法:http://zixuephp.net/article-430.html

//server.php
//创建websocket服务器对象,监听0.0.0.0:9501端口
$ws = new swoole_websocket_server("0.0.0.0", 9501);

$ws->set([
    'daemonize' => true,
    'worker_num' => 1,
    'heartbeat_check_interval' => 60,  //每60s检查一次心跳,遍历一次所有连接
    'heartbeat_idle_time' => 120,  //在这个时间内没有向服务器发送任何数据,此连接将被强制关闭
    'log_file' => '/usr/local/php/var/logs/swoole.log'
]);

//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
    //var_dump($request->fd);
    //var_dump($request->get);
    //var_dump($request->server);
    //$ws->push($request->fd, $request->fd);
});

//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
    $message = '';
    $message = $frame->data;
    $person = count($ws->connections);
    foreach($ws->connections as $fd){
        if($fd == $frame->fd){
            $message = json_decode($message,true);
            $message['self'] =1;
            $message['time'] =date('Y-m-d H:i:s',time());
            $message['person'] = $person;
            $message = json_encode($message);
            $ws->push($fd,$message);
        }else{
            $message = json_decode($message,true);
            $message['self'] =0;
            $message['time'] =date('Y-m-d H:i:s',time());
            $message['person'] = $person;
            $message = json_encode($message);
            $ws->push($fd, $message);
        }
    }
    //echo "message:".$message."\n";
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
    //echo "client-{$fd} is closed\n";
});

$ws->start();

三、php运行服务端

    nohup /usr/bin/php server.php &

[root@zixuephp /]# whereis php
php: /usr/bin/php /usr/local/php
[root@zixuephp /]# nohup /usr/bin/php server.php &
分享到:
0 0

*有问题之处烦请在评论中指出非常感谢!
不是我想要的内容,继续搜索:

扫描二维码手机查看

发布评论:


登录:
  表情:
评论话题
推荐阅读:
linux php7安装yaf扩展   阅读:8187面试的时候和你谈理想,是理想or入坑?   阅读:10133php 使用 smtp.php 类在线发送邮件功能   阅读:5583nginx安装mysql和json模块   阅读:4724centos 7 开启网络   阅读:6752移动端js触摸touch详解(附带案例源码)   阅读:16358mongodb设置shell开机启动脚本   阅读:9781mysql的四种索引类型   阅读:22190知乎百万赞作者告诉你:年薪百万的人都在靠什么赚钱   阅读:6260给网站添加一键qq登录的功能   阅读:7205用php从1加到100的值   阅读:8378mysql5.7主从同步配置   阅读:5296centos 7 安装 php-7.1.3   阅读:19695php设置cookie为HttpOnly防止XSS攻击   阅读:12440浅谈javascript的函数节流   阅读:4489分享:淘宝技术这十年   阅读:4555mongodb设置shell开机启动脚本   阅读:9781php swoole搭建简单的聊天室   阅读:3693shell脚本破解十位数内的所有纯数字rar加密压缩包脚本   阅读:8722centos 7 安装 php-7.1.3   阅读:19695centos 7 安装 redis 3.2.9   阅读:6449shell脚本破解十位数内的所有纯数字rar加密压缩包脚本   阅读:8722shell发送邮件脚本   阅读:7490小米手机端商城rem适配原理   阅读:6560网站性能优化-页面静态缓存   阅读:5323centos7.3安装mongodb3.6   阅读:7261mysql5.7主从同步中binlog同步模式详解   阅读:6828php冒泡排序法   阅读:13985简单的DOS攻击之死亡之ping详解   阅读:54036用php从1加到100的值   阅读:8378给网站添加一键qq登录的功能   阅读:7205phpexcel 超简单从excel表格一键导入数据到数据库教程   阅读:12022php打印九九乘法表   阅读:9956网站性能优化-页面静态缓存   阅读:5323霍金24岁博士毕业论文在线预览   阅读:5421php压缩页面的html代码一行显示   阅读:7174centos 7 添加 redis 3.2.9 开机启动脚本   阅读:9221crontab+shell脚本实现定时备份mysql数据库   阅读:7467php 统计网页打开耗时和脚本运行内存   阅读:6604javascript获取两个日期间的所有日期   阅读:6405linux php7编译安装mongodb扩展   阅读:8638phpexcel 超简单从excel表格一键导入数据到数据库教程   阅读:12022shell脚本破解十位数内的所有纯数字rar加密压缩包脚本   阅读:8722shell脚本破解十位数内的所有纯数字rar加密压缩包脚本   阅读:8722centos 7 安装 php-7.1.3   阅读:19695web项目高并发量网站解决方案   阅读:4480霍金24岁博士毕业论文在线预览   阅读:5421centos 7 安装 mysql-5.7   阅读:6815shell脚本统计当前服务器并发连接数   阅读:7227知乎百万赞作者告诉你:年薪百万的人都在靠什么赚钱   阅读:6260