ThinkPHP使用Swoole需要安裝 think-swoole Composer
包,前提系統(tǒng)已經(jīng)安裝好了Swoole PECL 拓展
tp5的項(xiàng)目根目錄下執(zhí)行composer命令安裝think-swoole:
composer require topthink/think-swoole
話不多說(shuō),直接上代碼:
新建WebSocket.php控制器:
(監(jiān)聽(tīng)端口要確認(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)聽(tīng)所有地址
protected $port = 9501; //監(jiān)聽(tīng)9501端口
protected $serverType = 'socket';
protected $option = [
'worker_num'=> 4, //設(shè)置啟動(dòng)的Worker進(jìn)程數(shù)
'daemonize' => false, //守護(hù)進(jìn)程化(上線改為true)
'backlog' => 128, //Listen隊(duì)列長(zhǎng)度
'dispatch_mode' => 2, //固定模式,保證同一個(gè)連接發(fā)來(lái)的數(shù)據(jù)只會(huì)被同一個(gè)worker處理
//心跳檢測(cè):每60秒遍歷所有連接,強(qiáng)制關(guān)閉10分鐘內(nèi)沒(méi)有向服務(wù)器發(fā)送任何數(shù)據(jù)的連接
'heartbeat_check_interval' => 60,
'heartbeat_idle_time' => 600
];
//建立連接時(shí)回調(diào)函數(shù)
public function onOpen($server,$req)
{
$fd = $req->fd;//客戶端標(biāo)識(shí)
$uid = $req->get['uid'];//客戶端傳遞的用戶id
$token = $req->get['token'];//客戶端傳遞的用戶登錄token
//省略token驗(yàn)證邏輯......
if (!$token) {
$arr = array('status'=>2,'message'=>'token已過(guò)期');
$server->push($fd, json_encode($arr));
$server->close($fd);
return;
}
//省略給用戶綁定fd邏輯......
echo "用戶{$uid}建立了連接,標(biāo)識(shí)為{$fd}\n";
}
//接收數(shù)據(jù)時(shí)回調(diào)函數(shù)
public function onMessage($server,$frame)
{
$fd = $frame->fd;
$message = $frame->data;
//省略通過(guò)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)閉時(shí)回調(diào)函數(shù)
public function onClose($server,$fd)
{
echo "標(biāo)識(shí){$fd}關(guān)閉了連接\n";
}
}
前端演示頁(yè)面:
(省略控制器判斷登錄狀態(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);
//錯(cuò)誤提示
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();//向上滾動(dòng)
},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)目根目錄開(kāi)啟服務(wù):
php public/index.php Websocket/start
這里的路徑,是因?yàn)槲医壎薶ome模塊為默認(rèn)模塊,tp5默認(rèn)情況是:php public/index.php index/Websocket/start)
開(kāi)啟成功,查看端口已經(jīng)被監(jiān)聽(tīng):
lsof -i:9501
很多PHPer在進(jìn)階的時(shí)候總會(huì)遇到一些問(wèn)題和瓶頸,業(yè)務(wù)代碼寫(xiě)多了沒(méi)有方向感,不知道該從那里入手去提升,對(duì)此我整理了一些資料,包括但不限于:分布式架構(gòu)、高可擴(kuò)展、高性能、高并發(fā)、服務(wù)器性能調(diào)優(yōu)、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優(yōu)化、shell腳本、Docker、微服務(wù)、Nginx等多個(gè)知識(shí)點(diǎn)高級(jí)進(jìn)階干貨需要的可以免費(fèi)分享給大家 ,需要 請(qǐng)戳這里
總結(jié)
以上所述是小編給大家介紹的PHP框架實(shí)現(xiàn)WebSocket在線聊天通訊系統(tǒng),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
您可能感興趣的文章:- php+websocket 實(shí)現(xiàn)的聊天室功能詳解
- PHP 實(shí)現(xiàn) WebSocket 協(xié)議原理與應(yīng)用詳解
- PHP用swoole+websocket和redis實(shí)現(xiàn)web一對(duì)一聊天
- ThinkPHP5.0框架結(jié)合Swoole開(kāi)發(fā)實(shí)現(xiàn)WebSocket在線聊天案例詳解
- PHP實(shí)現(xiàn)websocket通信的方法示例
- php redis 處理websocket聊天記錄的實(shí)例代碼
- PHP實(shí)現(xiàn)WebSocket實(shí)例詳解