Home  >  Article  >  PHP Framework  >  How to use Workerman to implement a real-time data visualization system

How to use Workerman to implement a real-time data visualization system

WBOY
WBOYOriginal
2023-11-07 08:48:14639browse

How to use Workerman to implement a real-time data visualization system

Workerman is a high-performance PHP socket framework developed based on PHP. It is used to develop network applications and has the advantages of efficiency, stability, and scalability. The biggest feature is that it supports high concurrency and can handle millions of TCP connections.

In this article, we will introduce how to use Workerman to implement a real-time data visualization system, including how to use Workerman to build a WebSocket server, how to use JavaScript's WebSocket API to obtain real-time data, and how to use the tool library D3.js to draw visualizations chart.

  1. Installing Workerman

The installation of Workerman is very simple. It is recommended to use Composer for installation. Perform the following operations in the terminal:

composer require workerman/workerman
  1. Build a WebSocket server

The steps to build a WebSocket server are as follows:

  1. Create a WebSocket server file server .php, the code is as follows:
require_once __DIR__ . '/vendor/autoload.php';  

use WorkermanWorker;
use WorkermanLibTimer;
use WorkermanConnectionTcpConnection;

$ws_worker = new Worker("websocket://0.0.0.0:2346");

$ws_worker->onConnect = function (TcpConnection $connection) {
    echo "client connected
";
};

$ws_worker->onMessage = function (TcpConnection $connection, $data) {
    $connection->send(json_encode(array(
        'value' => rand(1, 100)
    )));
};

$ws_worker->onClose = function (TcpConnection $connection) {
    echo "client closed
";
};

$ws_worker->onWorkerStart = function (Worker $ws_worker) {
    // 每隔1秒钟向所有客户端推送一次随机数据
    Timer::add(1, function () use ($ws_worker) {
        foreach ($ws_worker->connections as $connection) {
            $connection->send(json_encode(array(
                'value' => rand(1, 100)
            )));
        }
    });
};

Worker::runAll();

The code mainly implements the following functions:

  • Create WebSocket server;
  • Listen to client connection events;
  • Listen to the event of the client sending a message;
  • Listen to the event of the client closing the connection;
  • When the server starts, push random data to all clients regularly.
  1. Run the WebSocket server in the terminal:
php server.php start
  1. Get real-time data using JavaScript

In the browser The code for obtaining real-time data using JavaScript's WebSocket API is as follows:

var ws = new WebSocket('ws://localhost:2346');  

ws.onmessage = function (event) {  
    var data = JSON.parse(event.data);  
    console.log(data.value);  
}

The code mainly implements the following functions:

  • Creates a WebSocket connection;
  • sends data after receiving it from the server When, parse the data and output it on the console.
  1. Use D3.js to draw visual charts

The code for using D3.js to draw visual charts in the browser is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Realtime Data Visualization</title>
    <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>  
    var data = [];

    var width = 800;
    var height = 500;

    var svg = d3.select('body')
        .append('svg')
        .attr('width', width)
        .attr('height', height);

    var xScale = d3.scaleLinear()
        .range([0, width])
        .domain([0, 10]);

    var yScale = d3.scaleLinear()
        .range([height, 0])
        .domain([0, 100]);

    var line = d3.line()
        .x(function (d) {
            return xScale(d.index);
        })
        .y(function (d) {
            return yScale(d.value);
        });

    var path = svg.append('path')
        .attr('fill', 'none')
        .attr('stroke', 'steelblue')
        .attr('stroke-width', '1');

    var shift = 0;
    ws.onmessage = function (event) {
        var dataItem = JSON.parse(event.data);

        // 添加新数据
        data.push({
            index: shift,
            value: dataItem.value
        });

        // X轴平移
        if (shift >= 10) {
            shift--;
        }

        // 更新数据的X轴位置
        data.forEach(function (d) {
            d.index = d.index + 1;
        });

        // 更新路径数据
        path.attr('d', line(data));

        shift++;
    };
</script>
</body>
</html>

The code mainly implements the following functions:

  • Create SVG elements;
  • Define the scale;
  • Define the path generator;
  • Add path elements;
  • Receive real-time data and update path data.

So far, we have completed all the code to implement a real-time data visualization system using Workerman, JavaScript and D3.js. Open the HTML file in your browser and you can see a constantly updating line chart representing the random numbers being pushed continuously.

The above is the detailed content of How to use Workerman to implement a real-time data visualization system. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn