php實現(xiàn)即時聊天(基于融云通訊),目前只是簡單的事例。
今天看到了一個挺有意思的項目躯肌,即時聊天工具。雖然有QQ這樣很普及的聊天工具了破衔,但是自己搞一個還是挺有意思的清女。
本案例是基于融云通訊的,官網(wǎng)地址http://www.rongcloud.cn/晰筛,功能很多校仑,我由于沒有很好看的頁面,直接用他們的插件传惠,據(jù)我觀察,插件只有最近聯(lián)系人這個功能稻扬。那就先按照簡單的案例先實現(xiàn)吧卦方,喜歡的可以自己繼續(xù)研究!
首先需要注冊一個融云賬號---然后自己去創(chuàng)建一個實例----查看各種KEY泰佳,具體的自己按照官網(wǎng)的指引去看吧盼砍。我給的例子是我的一個測試key,可以直接去用逝她。依舊是tp5框架浇坐,自己不會配置tp5框架的,我就不說什么了黔宛。沒有用數(shù)據(jù)庫去實現(xiàn)用戶信息近刘,簡單的實現(xiàn)功能,主要是給大家演示一下功能臀晃,勿噴啊觉渴。
配置各種key的config.php
<?php
//配置文件
return [
'APP_KEY' => 'e0x9wycfxxx5q',
'APP_SECRET' => 'F7sI8rkLtv'
];
復(fù)制代碼
他們給的key好短啊有沒有,繼續(xù)吧徽惋。我下載了官方給的SDK案淋,已經(jīng)引入到extend文件下了∠栈妫可以直接調(diào)用了踢京。開始主要的部分吧,聊天頁面的主方法:
Index.php
<?php
namespace app\index\controller;
use rongyun\ServerAPI;
use think\Controller;
class Index extends Controller
{
public function _initialize()
{
if( empty( cookie('uid') ) ){
$this->redirect( url('login/index') );
}
}
//聊天主方法
public function index()
{
$appKey = config('APP_KEY');
$appSecret = config('APP_SECRET');
$rongYun = new ServerAPI( $appKey, $appSecret );
$tx = "http://www.tk.com/static/images/1.jpg";
if( 2 == cookie('uid') ){
$tx = "http://www.tk.com/static/images/2.jpg";
}
$token = $rongYun->getToken( cookie('uid'), cookie('uname'), $tx );
$token = json_decode( $token, true )['token'];
$this->assign([
'token' => $token
]);
return $this->fetch();
}
//所有的用戶信息
public function userInfo()
{
$return['userlist'] = [
['id' => 1, 'name' => '張三', 'portraitUri' => 'http://www.tk.com/static/images/1.jpg'],
['id' => 2, 'name' => '李四', 'portraitUri' => 'http://www.tk.com/static/images/2.jpg']
];
return json( $return );
}
//登錄用戶信息
public function onLine()
{
$return['data'] = [
['id' => '1', 'status' => true],
['id' => '2', 'status' => true]
];
return json( $return );
}
}
復(fù)制代碼
各種代碼我都寫死了宦棺,主要是演示效果的瓣距。好了,其余的代碼代咸,可以去我的github上去下載自己去官網(wǎng)對照這個看吧旨涝。我主要演示一下具體怎么跑起來。看一下login.php吧:
<?php
namespace app\index\controller;
use think\Controller;
class Login extends Controller
{
public function index()
{
return $this->fetch();
}
public function doLogin()
{
$param = input('param.');
if( '張三' == $param['uname'] ){
cookie('uid', 1);
cookie('uname', '張三');
}else if( '李四' == $param['uname'] ){
cookie('uid', 2);
cookie('uname', '李四');
}
$this->redirect( url('index/index') );
}
}