thinkphp 和 Gatewayworker整合web聊天2.0

weixin_33976072發表於2017-08-07

繼續上篇文章(連結),把功能新增到專案裡面
專案使用thinkphp3.2.3開發
現在主要做手機端功能,頁面也是手機端的頁面,用到了vue,js,可以實現訊息自動滾動到底部的最新訊息
更多歷史訊息往上滾動檢視
頁面和樣式程式碼如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title>web chat</title>
<style type="text/css">
*{margin: 0;padding: 0;}
html,body,#page{width: 100%;height: 100%;}
#page{position: relative;}
#page header{width: 100%;height: 45px;color: white;font-size: 15px;position: relative;text-align: center;background: #40a2fe;line-height: 45px;}
#page header .logo{position: absolute;width: 33px;height: 33px;border-radius: 50%;left: 10px;top: 6px;}
#page header .logo img{width: 100%;height: 100%;display: block;border-radius: 50%;}
#page .msg-box{position: absolute;top: 45px;left: 0;right: 0;bottom: 38px;overflow: auto;}
#page .msg-box ul{}
#page .msg-box ul li{font-size: 14px;list-style: none;overflow: auto;}
#page .msg-box ul .all-list{}
#page .msg-box ul .all-list img{width: 45px;height: 45px;border-radius: 50%;display: block;margin: 8px;float: left;}
#page .msg-box ul .all-list p{max-width: 239px;padding: 12px;float: left;background: #a2d6f3;color: #000;border: 1px solid #91c9e9;border-radius: 5px;box-shadow: 2px 2px #369bdb;margin-top: 15px;word-wrap:break-word; word-break:normal;}
/*#page .msg-box ul .all-list:after{content: "";clear: both;visibility: hidden;height: 0;}*/
#page .msg-box ul .muchlist{padding: 10px;text-align: center;}
#page .msg-box ul li a{padding: 5px 10px;background: #e2e2e2;text-decoration: none;font-size: 12px;border-radius: 5px;color: #666;}
#page .msg-box ul li a:hover{text-decoration: none;}
#page .msg-box ul .right p{box-shadow: -2px 2px #369bdb;float: right;}
#page .msg-box ul .right img{float: right;}
#page .send-box{position: absolute;left: 0;width: 100%;bottom: 0;background: #CECECE;height: 38px;text-align: center;}
#page .send-box input{width: 298px;height: 30px;font-size: 12px;border: 1px solid #fff;border-radius: 5px;margin-top: 3px;}
#page .send-box button{height: 30px;padding: 0 10px;border:1px solid #cecece;color: white;}
/*.right{text-align: right;}
li{list-style: none;}
ul{width: 80%;margin: 0 auto;border: 1px solid #cecece;}
.muchlist{color: lightblue;text-align: center;font-size: 12px;margin-bottom: 10px;padding: 6px;}*/
</style>
</head>
<body>
<div id="page">
    <header>
        <div class="logo">
            ![](__PUBLIC__/images/pic.jpg)
        </div>
        接收者<select id="uid">
            <for start="1" end="20">
            <option value="{$i}">{$i} 號</option>
            </for>
        </select>
    </header>
    <div class="msg-box">
        <ul id="charBox" style="height: 100%; overflow-x:auto;">
            <li class="muchlist" id="more_data_btn">
                <a href="javascript:void(0)" onclick="more_data()">檢視更多歷史訊息</a>
            </li>
            <li v-for="item in items" :class="{right:item.right}" class="all-list">
                ![](item.imgsrc)
                <p>{{item.text}}</p>
            </li>
        </ul>           
        
    </div>
    <div class="send-box">
        <input type="hidden" name="uid" id="uid2" value="1">
        <input type="text" name="msg" id="msg" value=""/>
        <button id="send">傳送</button>
    </div>
</div>
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>

<script>
var scroll_bottom = true; // 全域性變數,是否滾動到底部
var data_length = 0; // 全域性變數,vue裡面獲取新加入的歷史資料的長度
$(function() {
    $("#send").click(function() {
        send_msg();
    });
    $('#msg').keyup(function(event) {
        if(event.keyCode===13){
            send_msg();
        }
    });
});
function send_msg(){
    var uid = $('#uid').val();
    var msg = $('#msg').val();
    $.post("{:U('Index/message')}", {
        uid: uid,
        msg: msg
    },
    function(data) {
        $('#msg').val('');
    });
}
function more_data(){
    var uid = $('#uid').val();
    $.post("{:U('Index/more_msg')}", {
        uid: uid
    },
    function(data) {
        if(data == 'null'){
            $('#more_data_btn').hide();
            alert('沒有更多訊息了');
            return false;
        }
        scroll_bottom = false;
        var dataxx = JSON.parse(data)
        data_length = dataxx.length;
        for (var i = 0; i < data_length; i++) {
            dataIm.unshift(dataxx[i]);
        }
    });
}
</script>  


<script type="text/javascript">
var dataIm = {$arr['json']};
var vm = new Vue({
    el:"#page",
    data:{
        items:dataIm
    },
    computed:{
        msgbox(){
            return document.getElementById("charBox")
        }
    },
    updated:function(){
        console.log(scroll_bottom);
         if(scroll_bottom == true){
            this.msgbox.scrollTop=this.msgbox.scrollHeight
         }else{
            scroll_bottom = true;
            var li = document.getElementById('charBox').getElementsByTagName('li');
            var liheight = 0;
            for(var i=0;i<data_length;i++){
                liheight += li[i].offsetHeight;
            }
            console.log(liheight);
            document.getElementById("charBox").scrollTop = liheight;
         }
    }
})

</script>
<script type="text/javascript"> 
function insert_data(received_msg){
    // console.log('插入訊息:'+received_msg);
    dataIm.push(received_msg);
    // console.log(dataIm+'-dataIm');
}

// 開啟一個 web socket 
var ws = new WebSocket("ws://127.0.0.1:8282");
ws.onopen = function() {};
ws.onmessage = function(evt) {
    var received_msg = evt.data;
    console.log(received_msg);
    var jmsg = JSON.parse(received_msg);
    if (jmsg.text) {
        insert_data(jmsg);
    }
    if (jmsg.client_id) {
        $.post("{:U('Index/bind')}", {
            client_id: jmsg.client_id
        },
        function(data) {
            console.log(data);
        });
    }
} 
</script> 
</body>
</html>

php程式碼如下:

<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public $uid = 10;
    public function index() {
        $this->display();
    } 
    public function chat() {
        $this->uid = I('uid');
        if($this->uid == 0) $this->error("請選擇使用者");
        session('uid', $this->uid);
        $this->assign('uid',$this->uid);

        // 此處查詢當前使用者的聊天記錄,輸出到頁面
        $list[0]['text'] = "ThinkPHP框架";
        $list[0]['right'] = 0;
        $list[0]['imgsrc'] = C('HOST').'/Public/images/pic.jpg';

        $list[1]['text'] = "Ci框架";
        $list[1]['right'] = 1;
        $list[1]['imgsrc'] = C('HOST').'/Public/images/pic.jpg';
        $arr['json'] = json_encode($list);
        if(count($list) < 1) $arr['json'] = '[]';
        $this->assign('arr',$arr);
        $this->display();
    } 

    function bind() { 
        $uid = session('uid');
        $client_id = I('client_id');
        $gateway = new \Org\Util\Gateway();
        $gateway->bindUid($client_id, $uid);
        $count = $gateway->getAllClientCount();
        $message = '繫結成功' . $uid . '-' . $client_id.'-共有'.$count.'個人線上';
        echo $message;
        // $gateway->sendToUid($uid, $message);
    } 

    function message() { 
        // 此處處理接收使用者發過來的訊息內容,儲存資料庫,推送給傳送者和接受者
        $to_uid = I('uid');
        $message = I('msg');
        $gateway = new \Org\Util\Gateway();
        $data['text'] = $message;
        $data['from_uid'] = session('uid');
        $data['to_uid'] = $to_uid;
        $data['right'] = 0;
$data['imgsrc'] = C('HOST').'/Public/images/pic.jpg';
        if ($gateway->isUidOnline($to_uid)) {
            // 判斷接受小時著是否線上,線上執行傳送訊息
            $gateway->sendToUid($to_uid, json_encode($data));
        }else{
            $data['text'] .= '[對方不線上]';
        }

$data['right'] = 1;
        $gateway->sendToUid($data['from_uid'], json_encode($data)); // 發給自己 
        
        echo json_encode($data);
    }

    function more_msg(){
        // 此處根據當前使用者和聊天使用者查詢資料返回聊天記錄陣列
        $list[0]['text'] = "1";
        $list[0]['right'] = 0;
        $list[0]['imgsrc'] = C('HOST').'/Public/images/pic.jpg';

        $list[1]['text'] = "2";
        $list[1]['right'] = 1;
        $list[1]['imgsrc'] = C('HOST').'/Public/images/pic.jpg';
        echo json_encode($list);
    }
}

相關文章