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

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

Nov 07, 2023 am 08:48 AM
Visualization workerman Real-time data

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
Copy after login
  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();
Copy after login

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
Copy after login
  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);  
}
Copy after login

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>
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement real-time data updates in ECharts How to implement real-time data updates in ECharts Dec 17, 2023 pm 02:07 PM

ECharts is an open source visual chart library that supports various chart types and rich data visualization effects. In actual scenarios, we often need to display real-time data, that is, when the data source changes, the chart can be updated immediately and present the latest data. So, how to achieve real-time data update in ECharts? The following is a specific code demonstration example. First, we need to introduce ECharts’ js files and theme styles: &lt;!DOCTYPEhtml&gt;

Implement file upload and download in Workerman documents Implement file upload and download in Workerman documents Nov 08, 2023 pm 06:02 PM

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

How to use php interface and ECharts to generate visual statistical charts How to use php interface and ECharts to generate visual statistical charts Dec 18, 2023 am 11:39 AM

In today's context where data visualization is becoming more and more important, many developers hope to use various tools to quickly generate various charts and reports so that they can better display data and help decision-makers make quick judgments. In this context, using the Php interface and ECharts library can help many developers quickly generate visual statistical charts. This article will introduce in detail how to use the Php interface and ECharts library to generate visual statistical charts. In the specific implementation, we will use MySQL

How to implement the basic usage of Workerman documents How to implement the basic usage of Workerman documents Nov 08, 2023 am 11:46 AM

Introduction to how to implement the basic usage of Workerman documents: Workerman is a high-performance PHP development framework that can help developers easily build high-concurrency network applications. This article will introduce the basic usage of Workerman, including installation and configuration, creating services and listening ports, handling client requests, etc. And give corresponding code examples. 1. Install and configure Workerman. Enter the following command on the command line to install Workerman: c

Which one is better, swoole or workerman? Which one is better, swoole or workerman? Apr 09, 2024 pm 07:00 PM

Swoole and Workerman are both high-performance PHP server frameworks. Known for its asynchronous processing, excellent performance, and scalability, Swoole is suitable for projects that need to handle a large number of concurrent requests and high throughput. Workerman offers the flexibility of both asynchronous and synchronous modes, with an intuitive API that is better suited for ease of use and projects that handle lower concurrency volumes.

Five selections of visualization tools for exploring Kafka Five selections of visualization tools for exploring Kafka Feb 01, 2024 am 08:03 AM

Five options for Kafka visualization tools ApacheKafka is a distributed stream processing platform capable of processing large amounts of real-time data. It is widely used to build real-time data pipelines, message queues, and event-driven applications. Kafka's visualization tools can help users monitor and manage Kafka clusters and better understand Kafka data flows. The following is an introduction to five popular Kafka visualization tools: ConfluentControlCenterConfluent

Workerman development: How to implement real-time video calls based on UDP protocol Workerman development: How to implement real-time video calls based on UDP protocol Nov 08, 2023 am 08:03 AM

Workerman development: real-time video call based on UDP protocol Summary: This article will introduce how to use the Workerman framework to implement real-time video call function based on UDP protocol. We will have an in-depth understanding of the characteristics of the UDP protocol and show how to build a simple but complete real-time video call application through code examples. Introduction: In network communication, real-time video calling is a very important function. The traditional TCP protocol may have problems such as transmission delays when implementing high-real-time video calls. And UDP

How to use Workerman to build a high-availability load balancing system How to use Workerman to build a high-availability load balancing system Nov 07, 2023 pm 01:16 PM

How to use Workerman to build a high-availability load balancing system requires specific code examples. In the field of modern technology, with the rapid development of the Internet, more and more websites and applications need to handle a large number of concurrent requests. In order to achieve high availability and high performance, the load balancing system has become one of the essential components. This article will introduce how to use the PHP open source framework Workerman to build a high-availability load balancing system and provide specific code examples. 1. Introduction to Workerman Worke

See all articles