今天看到了一個挺有意思的項目,即時聊天工具。雖然有QQ這樣很普及的聊天工具了,但是自己搞一個還是挺有意思的。
本案例是基於融雲通訊的,官網地址http://www.rongcloud.cn/,功能很多,我由於沒有很好看的頁面,直接用他們的插件,據我觀察,插件只有最近聯系人這個功能。那就先按照簡單的案例先實現吧,喜歡的可以自己繼續研究!
首先需要注冊一個融雲賬號---然后自己去創建一個實例----查看各種KEY,具體的自己按照官網的指引去看吧。我給的例子是我的一個測試key,可以 直接去用。依舊是tp5框架,自己不會配置tp5框架的,我就不說什么了。沒有用數據庫去實現用戶信息,簡單的實現功能,主要是給大家演示一下功能,勿噴 啊。
配置各種key的config.php
1 <?php 2 //配置文件 3 return [ 4 'APP_KEY' => 'e0x9wycfxxx5q', 5 'APP_SECRET' => 'F7sI8rkLtv' 6 ];
他們給的key好短啊有沒有,繼續吧。我下載了官方給的SDK,已經引入到extend文件下了。可以直接調用了。開始主要的部分吧,聊天頁面的主方法:
Index.php
1 <?php 2 namespace app\index\controller; 3 4 use rongyun\ServerAPI; 5 use think\Controller; 6 7 class Index extends Controller 8 { 9 public function _initialize() 10 { 11 if( empty( cookie('uid') ) ){ 12 $this->redirect( url('login/index') ); 13 } 14 } 15 16 //聊天主方法 17 public function index() 18 { 19 $appKey = config('APP_KEY'); 20 $appSecret = config('APP_SECRET'); 21 22 $rongYun = new ServerAPI( $appKey, $appSecret ); 23 24 $tx = "http://www.tk.com/static/images/1.jpg"; 25 if( 2 == cookie('uid') ){ 26 $tx = "http://www.tk.com/static/images/2.jpg"; 27 } 28 $token = $rongYun->getToken( cookie('uid'), cookie('uname'), $tx ); 29 30 $token = json_decode( $token, true )['token']; 31 $this->assign([ 32 'token' => $token 33 ]); 34 return $this->fetch(); 35 } 36 37 //所有的用戶信息 38 public function userInfo() 39 { 40 $return['userlist'] = [ 41 ['id' => 1, 'name' => '張三', 'portraitUri' => 'http://www.tk.com/static/images/1.jpg'], 42 ['id' => 2, 'name' => '李四', 'portraitUri' => 'http://www.tk.com/static/images/2.jpg'] 43 ]; 44 return json( $return ); 45 } 46 47 //登錄用戶信息 48 public function onLine() 49 { 50 $return['data'] = [ 51 ['id' => '1', 'status' => true], 52 ['id' => '2', 'status' => true] 53 ]; 54 return json( $return ); 55 } 56 }
各種代碼我都寫死了,主要是演示效果的。好了,其余的代碼,可以去我的github上去下載自己去官網對照這個看吧。我主要演示一下具體怎么跑起來。看一下login.php吧:
1 <?php 2 namespace app\index\controller; 3 4 use think\Controller; 5 6 class Login extends Controller 7 { 8 public function index() 9 { 10 return $this->fetch(); 11 } 12 13 public function doLogin() 14 { 15 $param = input('param.'); 16 17 if( '張三' == $param['uname'] ){ 18 cookie('uid', 1); 19 cookie('uname', '張三'); 20 }else if( '李四' == $param['uname'] ){ 21 22 cookie('uid', 2); 23 cookie('uname', '李四'); 24 } 25 26 $this->redirect( url('index/index') ); 27 } 28 }
哈哈,我的登錄只是為了區分用戶(真的做項目可不是這樣!)。可以看到吧,一個用戶是張三,一個用戶是李四。密碼亂輸就行。看一下演示效果吧:
首先訪問首頁,沒登錄的話會跳轉登錄:
如果你用的是張三登錄的話,記住:張三的id是1,很重要!用戶名正確進行,密碼亂輸就行。登錄之后,頁面如下:
輸入會話的ID,也就是用戶ID,我們向李四說話,李四就是2,然后點擊設置會話,會彈出如下頁面:
開始聊天吧:
然后重新打開一個瀏覽器,一定是另外一個瀏覽器!登錄,用李四去登錄,你會看到:
看到張三給你發信息了,打開看看吧:
也可以回復:
哈哈是不是很有意思。當然我現在只實現了最最簡單的功能,有興趣的可以繼續研究!
項目下載地址:https://github.com/nick-bai/talking,如果沒看到的話,項目正在上傳,稍后在看就可以看到了。對你有幫助的話,給我打個星。