workerman statistics online number implementation code: (recommended: workerman tutorial)
Server-side code
<?php use Workerman\Worker; use Workerman\Lib\Timer; require_once __DIR__ . '/Workerman/Autoloader.php'; $worker = new Worker('websocket://127.0.0.1:2345'); // 全局变量,保存当前进程的客户端连接数 $connection_count = 0; // 这个例子中进程数必须为1 $worker->count = 1; $worker->onConnect = function($connection) { // 有新的客户端连接时,连接数+1 global $connection_count; ++$connection_count; echo "now connection_count=$connection_count\n"; }; // 进程启动时设置一个定时器,定时向所有客户端连接发送数据 $worker->onWorkerStart = function($worker) { // 定时,每10秒一次 Timer::add(1, function()use($worker) { global $connection_count; // 遍历当前进程所有的客户端连接,发送当前服务器的时间 foreach($worker->connections as $connection) { $connection->send($connection_count); } }); }; $worker->onClose = function($connection) { // 客户端关闭时,连接数-1 global $connection_count; $connection_count--; echo "now connection_count=$connection_count\n"; }; // 运行worker Worker::runAll();
When the client The callback function triggered when a connection is established with Workerman (after the TCP three-way handshake is completed). The onConnect callback will only be triggered once per connection.
The callback function triggered when the client connection is disconnected from Workerman. No matter how the connection is disconnected, onClose will be triggered as soon as it is disconnected. onClose will only be triggered once per connection.
Client code
<?php ?> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> function ds(){ $.get('127.0.0.1:2345',function(data,status){ console.log("Data: " + data + "nStatus: " + status); }) } // window.setInterval(ds,1000); ws = new WebSocket("ws://127.0.0.1:2345"); ws.onopen = function() { //alert("连接成功"); //ws.send('tom'); //alert("给服务端发送一个字符串:tom"); }; ws.onmessage = function(e) { //alert("收到服务端的消息:" + e.data); console.log("收到服务端的消息:" + e.data); }; </script>
The above is the detailed content of How does workerman count the number of people online?. For more information, please follow other related articles on the PHP Chinese website!