本文實(shí)例講述了ThinkPHP5.0框架結(jié)合Swoole開發(fā)實(shí)現(xiàn)WebSocket在線聊天案例。分享給大家供大家參考,具體如下:
ThinkPHP使用Swoole需要安裝 think-swoole Composer包,前提系統(tǒng)已經(jīng)安裝好了Swoole PECL 拓展(相關(guān)文章:Linux下源碼包安裝使用Swoole擴(kuò)展)
在tp5的項(xiàng)目根目錄下執(zhí)行composer命令安裝think-swoole:
composer require topthink/think-swoole
安裝成功:
話不多說,直接上代碼:
新建WebSocket.php控制器:
(監(jiān)聽端口要確認(rèn)服務(wù)器放行,寶塔環(huán)境還需要添加安全組規(guī)則)
?php
namespace app\home\controller;
use think\swoole\Server;
class WebSocket extends Server
{
protected $host = '0.0.0.0'; //監(jiān)聽所有地址
protected $port = 9501; //監(jiān)聽9501端口
protected $serverType = 'socket';
protected $option = [
'worker_num'=> 4, //設(shè)置啟動的Worker進(jìn)程數(shù)
'daemonize' => false, //守護(hù)進(jìn)程化(上線改為true)
'backlog' => 128, //Listen隊列長度
'dispatch_mode' => 2, //固定模式,保證同一個連接發(fā)來的數(shù)據(jù)只會被同一個worker處理
//心跳檢測:每60秒遍歷所有連接,強(qiáng)制關(guān)閉10分鐘內(nèi)沒有向服務(wù)器發(fā)送任何數(shù)據(jù)的連接
'heartbeat_check_interval' => 60,
'heartbeat_idle_time' => 600
];
//建立連接時回調(diào)函數(shù)
public function onOpen($server,$req)
{
$fd = $req->fd;//客戶端標(biāo)識
$uid = $req->get['uid'];//客戶端傳遞的用戶id
$token = $req->get['token'];//客戶端傳遞的用戶登錄token
//省略token驗(yàn)證邏輯......
if (!$token) {
$arr = array('status'=>2,'message'=>'token已過期');
$server->push($fd, json_encode($arr));
$server->close($fd);
return;
}
//省略給用戶綁定fd邏輯......
echo "用戶{$uid}建立了連接,標(biāo)識為{$fd}\n";
}
//接收數(shù)據(jù)時回調(diào)函數(shù)
public function onMessage($server,$frame)
{
$fd = $frame->fd;
$message = $frame->data;
//省略通過fd查詢用戶uid邏輯......
$uid = 666;
$data['uid'] = $uid;
$data['message'] = '用戶'.$uid.'發(fā)送了:'.$message;
$data['post_time'] = date("m/d H:i",time());
$arr = array('status'=>1,'message'=>'success','data'=>$data);
//僅推送給當(dāng)前連接用戶
//$server->push($fd, json_encode($arr));
//推送給全部連接用戶
foreach($server->connections as $fd) {
$server->push($fd, json_encode($arr));
}
}
//連接關(guān)閉時回調(diào)函數(shù)
public function onClose($server,$fd)
{
echo "標(biāo)識{$fd}關(guān)閉了連接\n";
}
}
前端演示頁面:
(省略控制器判斷登錄狀態(tài)、分配數(shù)據(jù)邏輯......)
!DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8" />
meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
title>Chat/title>
link rel="stylesheet" type="text/css" href="/static/liaotian/chat.css" rel="external nofollow" />
script src="/static/liaotian/js/jquery.min.js">/script>
script src="/static/liaotian/js/flexible.js">/script>
/head>
body>
header class="header">
a class="back" href="javascript:history.back()" rel="external nofollow" >/a>
h5 class="tit">在線聊天/h5>
a href="">div class=" rel="external nofollow" right">退出/div>/a>
/header>
!-- 聊天內(nèi)容 start-->
div class="message"> /div>
!-- 聊天內(nèi)容 end-->
!-- 底部 start-->
div class="footer">
img id="setbtn" src="/static/liaotian/images/hua.png" alt="" />
img src="/static/liaotian/images/xiaolian.png" alt="" />
input type="text" id="msg" value="" maxlength="300">
p style="background: rgb(17, 79, 142);" id="sendBtn">發(fā)送/p>
/div>
!-- 底部 end-->
/body>
/html>
script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">/script>
script src="https://cdn.bootcss.com/layer/3.1.0/layer.js">/script>
script type="text/javascript">
$(function () {
var uid = 666;//當(dāng)前用戶id
var token = 'abcdefg';//用戶token
//判斷瀏覽器是否支持WebSocket
var supportsWebSockets = 'WebSocket' in window || 'MozWebSocket' in window;
if (supportsWebSockets) {
//建立WebSocket連接(ip地址換成自己主機(jī)ip)
var ws = new WebSocket("ws://127.0.0.1:9501?uid="+uid+"token="+token);
ws.onopen = function () {
layer.msg('服務(wù)器連接成功',{shade:0.1,icon:1,time:600});
};
ws.onerror = function () {
layer.msg('服務(wù)器連接失敗',{shade:0.1,icon:2,time:600});
};
ws.onmessage = function (evt) {
var data = $.parseJSON(evt.data);
//錯誤提示
if(data.status != 1){
layer.alert(data.message,{icon:2});
return;
}
//消息返回
if (data.status==1 data.data.message!='') {
var html = "";
if (data.data.uid == uid) {
html += "div style='word-break:break-all' class=\"show\">div class=\"time\">"+data.data.post_time+"/div>div class=\"msg\">img src=\""+data.data.head_img+"\" alt=\"\" />p>i clas=\"msg_input\">/i>"+data.data.message+"/p>/div>/div>";
}else{
html += "div style='word-break:break-all' class=\"send\">div class=\"time\">"+data.data.post_time+"/div>div class=\"msg\">img src=\""+data.data.head_img+"\" alt=\"\" />p>i clas=\"msg_input\">/i>"+data.data.message+"/p>/div>/div>";
}
}
$(".message").append(html);
setTimeout(function () {
($('.message').children("div:last-child")[0]).scrollIntoView();//向上滾動
},100);
};
ws.onclose = function (res) {
};
//按鈕發(fā)送
$("#sendBtn").click(function () {
var contents = $("#msg").val().trim();
if(contents == null || contents == ""){
layer.msg('內(nèi)容為空',{shade:0.1,icon:2,time:600});
return false;
}else{
ws.send(contents);
$("#msg").val("");
}
});
//回車發(fā)送
$("#msg").keydown(function (evel) {
var that = $(this);
if (evel.keyCode == 13) {
evel.cancelBubble = true;
evel.preventDefault();
evel.stopPropagation();
var contents = that.val().trim();
if(contents == null || contents == ""){
layer.msg('內(nèi)容為空',{shade:0.1,icon:2,time:600});
return false;
}else{
ws.send(contents);
that.val("");
}
}
});
}else{
layer.alert("您的瀏覽器不支持 WebSocket!");
}
});
/script>
服務(wù)器移到項(xiàng)目根目錄開啟服務(wù):
php public/index.php Websocket/start
(這里的路徑,是因?yàn)槲医壎薶ome模塊為默認(rèn)模塊,tp5默認(rèn)情況是:php public/index.php index/Websocket/start
)
開啟成功,查看端口已經(jīng)被監(jiān)聽:
lsof -i:9501
演示效果如下:
服務(wù)器監(jiān)聽如下:
用戶每刷新重連一次,fd標(biāo)識都會改變。
更多關(guān)于thinkPHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《ThinkPHP入門教程》、《thinkPHP模板操作技巧總結(jié)》、《ThinkPHP常用方法總結(jié)》、《codeigniter入門教程》、《CI(CodeIgniter)框架進(jìn)階教程》、《Zend FrameWork框架入門教程》及《PHP模板技術(shù)總結(jié)》。
希望本文所述對大家基于ThinkPHP框架的PHP程序設(shè)計有所幫助。
您可能感興趣的文章:- php+websocket 實(shí)現(xiàn)的聊天室功能詳解
- PHP 實(shí)現(xiàn) WebSocket 協(xié)議原理與應(yīng)用詳解
- PHP框架實(shí)現(xiàn)WebSocket在線聊天通訊系統(tǒng)
- PHP用swoole+websocket和redis實(shí)現(xiàn)web一對一聊天
- PHP實(shí)現(xiàn)websocket通信的方法示例
- php redis 處理websocket聊天記錄的實(shí)例代碼
- PHP實(shí)現(xiàn)WebSocket實(shí)例詳解