workerman?統(tǒng)計在線人數(shù)實現(xiàn)代碼:
服務(wù)器端代碼
<?php
useWorkerman\Worker;
useWorkerman\Lib\Timer;
require_once__DIR__ . '/Workerman/Autoloader.php';
$worker= newWorker('websocket://127.0.0.1:2345');
// 全局變量提鸟,保存當(dāng)前進程的客戶端連接數(shù)
$connection_count= 0;
// 這個例子中進程數(shù)必須為1
$worker->count= 1;
$worker->onConnect = function($connection)
{
????// 有新的客戶端連接時瓶您,連接數(shù)+1
????global$connection_count;
????++$connection_count;
????echo"now connection_count=$connection_count\n";
};
// 進程啟動時設(shè)置一個定時器探入,定時向所有客戶端連接發(fā)送數(shù)據(jù)
$worker->onWorkerStart = function($worker)
{
????// 定時,每10秒一次
????Timer::add(1, function()use($worker)
????{
????????global$connection_count;
????????// 遍歷當(dāng)前進程所有的客戶端連接,發(fā)送當(dāng)前服務(wù)器的時間
????????foreach($worker->connections as$connection)
????????{
????????????$connection->send($connection_count);
????????}
????});
};
$worker->onClose = function($connection)
{
????// 客戶端關(guān)閉時泌辫,連接數(shù)-1
????global$connection_count;
????$connection_count--;
????echo"now connection_count=$connection_count\n";
};
// 運行worker
Worker::runAll();
當(dāng)客戶端與Workerman建立連接時(TCP三次握手完成后)觸發(fā)的回調(diào)函數(shù)叉跛。每個連接只會觸發(fā)一次onConnect回調(diào)。
當(dāng)客戶端連接與Workerman斷開時觸發(fā)的回調(diào)函數(shù)跋理。不管連接是如何斷開的择克,只要斷開就會觸發(fā)onClose。每個連接只會觸發(fā)一次onClose前普。
客戶端代碼
<?php
?>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
?functionds(){
????????$.get('127.0.0.1:2345',function(data,status){
????????????console.log("Data: "+ data + "nStatus: "+ status);
????????????})
?????}
// window.setInterval(ds,1000);
ws = newWebSocket("ws://127.0.0.1:2345");
ws.onopen = function() {
????//alert("連接成功");
????//ws.send('tom');
????//alert("給服務(wù)端發(fā)送一個字符串:tom");
};
ws.onmessage = function(e) {
????//alert("收到服務(wù)端的消息:" + e.data);
????console.log("收到服務(wù)端的消息:"+ e.data);
};
</script>
本文來自PHP中文網(wǎng)的workerman教程欄目:https://www.php.cn/workerman/