swoole搭建聊天室实例代码

2018-06-24 09:47

阅读:286

如何通过swoole搭建一个简单的聊天室呢。请看一下代码,这里主要用到了websocket构建。


swoole代码:

<?php$server = new swoole_websocket_server("0.0.0.0",8095);
$max = 0;
$server->set(array(    'daemonize' => true,
));
$server->on('open', function (swoole_websocket_server $server, $req) {    //每一次客户端连接 最大连接数将增加  
    
        $link = mysqli_connect('localhost','root','xxxxx','xxxxx');
        $queryStr = "SELECT * FROM message order by id desc limit 10";
        $res = mysqli_query($link,$queryStr);
        $data = array();        while($row = $res->fetch_assoc())
        {                //$row['content'] = htmlentitles($row['content']); 
                $data[] = $row;
        }
        mysqli_close($link);        if(count($data) > 0){

        //过滤一些不好的词
        $badword = array(            '草','艹','逼','妈','干你','骚','搔','sao','日','党','娘','司机','黄','色','https','鸡','妓','嫖'
        );        //$badword1 = array_combine($badword,array_fill(0,count($badword),'*'));    

        foreach($data as $k=>$v){
                $badword1 = array_combine($badword,array_fill(0,count($badword),'*'));
                $res = strtr($v['content'], $badword1);
                $data[$k]['content'] = htmlentities($res);
        }
        }
        $end = json_encode($data);
        $fd = $req->fd;
        $server->push($fd,'firstFlag_c_'.$end);
});

$server->on('message', function (swoole_websocket_server $server, $frame) {
    $fds   = $frame->fd;
    $data = $frame->data;
    $time = date('Y-m-d H:i:s');     #$message = "连接号{$fd}:内容:{$data}";
    $dataArr = explode('_c_',$data);
    $dataIn = array();    //$dataIn['name'] = $dataArr[0];
    //$dataIn['content'] = $dataArr[1];
                       //$dataIn['created_at'] = date('Y-m-d H:i:s');
    $message = $dataArr[0]."_c_".htmlspecialchars($dataArr[1])."_c_".$dataArr[2]."_c_".date('Y-m-d H:i:s');
    $link = mysqli_connect('localhost','root','xxxxxx','xxxxx');    if(!link){

        $message = 'k_c_connect false_c_22';
    }
    $queryStr = "INSERT INTO message (`name`,`content`,`img`,`created_at`) VALUES ('".$dataArr[0]."','".$dataArr[1]."','".$dataArr[2]."','".$time."')";    if(mysqli_query($link,$queryStr) == true){

    }else{
        $message = 'k_c_insert false_c_22';
    }
    mysqli_close($link);    global $max;    //向所有人广播  
        $badword = array(            '草','艹','逼','妈','干你','骚','搔','sao','日','党','娘','司机','黄','色','https','pan.baidu','鸡','妓','嫖'
        );    foreach ($server->connections as $fd) {        echo PHP_EOL . time('Y-m-d h:m:s') . ': ' . $fd . " : " . $data;       // $server->push($i, $message); 
        if($fds == $fd){
                $messages = $message.'_c_right';
        }else{
                $messages = $message.'_c_left';
        }
        $badword1 = array_combine($badword,array_fill(0,count($badword),'*'));
        $messages = htmlentities(strtr($messages, $badword1));
        $server->push($fd, $messages);
    }
});

$server->on('close', function (swoole_websocket_server $server, $fd) {    //关闭连接 连接减少  
    global $max;
    $max--;    echo "client {$fd} closed\n";
});

$server->start();


前端的javascript代码:

<script type="text/javascript">
    var exampleSocket = new WebSocket("ws://xxx.xxx.xx.xxx:8095");
    exampleSocket.onopen = function (event) {        var name = $('#user_login_name').val();        var img = $('#user_login_img').val();
        exampleSocket.send(name+"_c_"+name+"已连接!_c_"+img);
    };
    exampleSocket.onmessage = function (event) {
    var data = event.data;        var dataArr = data.split('_c_');        var list = $("#chatlist");        var initStr = '';        if(dataArr[0] == 'firstFlag'){            var res = eval("("+dataArr[1]+")");            var num = res.length;            for(var i = num-1;i>=0;i--){
                initStr += '<li style="margin-top: 6px;">' +                        '<div class="sender">'+                        '<div>'+                        '<img src="'+res[i]['img']+'">'+                        '</div>'+                        '<div>'+                        '<div class="left_triangle"></div>'+                        '<span>'+res[i]['content']+'</span>'+                        '</div>'+                        '</div>'+                        '</li>';
            }
            list.append(initStr);            var div = document.getElementById('chatlist');
            div.scrollTop = div.scrollHeight;            return false;
        }        var strLeft = '<li style="margin-top: 6px;">' +                '<div class="sender">'+                '<div>'+                '<img src="'+dataArr[2]+'">'+                '</div>'+                '<div>'+                '<div class="left_triangle"></div>'+                '<span>'+dataArr[1]+'</span>'+                '</div>'+                '</div>'+                '</li>';        var strRight = '<li style="margin-top: 6px;">' +                '<div class="receiver">'+                '<div>'+                '<img src="'+dataArr[2]+'">'+                '</div>'+                '<div>'+                '<div class="right_triangle"></div>'+                '<span>'+dataArr[1]+'</span>'+                '</div>'+                '</div>'+                '</li>';        if(dataArr[4] == 'left'){
            list.append(strLeft);
        }else{
            list.append(strRight);
        }        var divs = document.getElementById('chatlist');
        divs.scrollTop = divs.scrollHeight;
    };

    $("#post-share").click(function(){        var content = $('#post-share-content').val();        if(content.match(/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g)){
            layer.msg('此处不能发网址哦!');            return false;
        }        var name = $('#user_login_name').val();        var img = $('#user_login_img').val();        var str = name+'_c_'+content+'_c_'+img;
        exampleSocket.send(str);
        $('#post-share-content').val('');
    });


html代码:

<div class="am-u-sm-12">
    <div class="am-panel  am-panel-warning" style="margin-bottom: 6px;">
        <div class="am-panel-hd">聊天内容</div>
        <div id="chatroom" style="overflow: hidden;">
            <div id="chatlist" style="width:100%;max-height: 500px;overflow-y: scroll;">

            </div>
        </div>
    </div>
</div>

<div class="am-u-sm-12" >
    <div class="am-panel am-panel-default" style="margin-bottom: 0;">
        <form class="am-form">
            <fieldset>
                <div class="am-form-group" style="margin-top: 0px;">
                    <textarea class="" rows="3" id="post-share-content" placeholder="输入聊天内容"></textarea>
                </div>

                <p style="margin-bottom:-15px;">
                    <button type="button" id="post-share" style="width: 100%;" class="am-btn am-btn-warning am-radius">发送</button>
                </p>
            </fieldset>
        </form>
    </div>
</div>


以上便完成了一个简单的聊天室,可以开心的聊天了。



评论


乖,登录后才可以留言!

热门文章

推荐文章

最新文章

置顶文章