search
HomePHP FrameworkWorkermanWorkerman development: How to implement an online voting system based on WebSocket protocol

Workerman development: How to implement an online voting system based on WebSocket protocol

In today's information age, online voting systems have become an indispensable part of elections, surveys and other activities. Compared with traditional voting methods, the online voting system is not only easy to operate, but also fast and can realize functions such as real-time statistics.

This article will introduce how to use PHP's Workerman framework to build an online voting system based on the WebSocket protocol. At the same time, specific code examples will be given for readers' reference.

1. What is Workerman?

Workerman is a high-performance, open source PHP asynchronous framework. It is based on event-driven ideas and can easily implement long-connection applications, such as WebSocket, instant messaging and other applications.

Workerman supports protocols such as TCP, UDP and HTTP, and has the characteristics of high concurrency and low memory consumption. Compared with traditional web applications, Workerman has stronger real-time performance and stability, so it is suitable for application scenarios such as online games, chat rooms, barrage, and message push.

2. Build a WebSocket server

Before we begin, we need to ensure that the PHP environment has been installed and the Workerman framework has been installed. For specific installation procedures, please refer to the official documentation.

Next, we need to create a new PHP file to start the WebSocket server and listen to the messages sent by the client. Suppose we open the WebSocket service on the 8080 port of the local 127.0.0.1, the code is as follows:

<?php
require_once __DIR__ . '/vendor/autoload.php';

use WorkermanWorker;
use WorkermanWebServer;
use WorkermanProtocolsWebsocket;

$ws_worker = new Worker('websocket://127.0.0.1:8080');
$ws_worker->count = 1;

$ws_worker->onWorkerStart = function() {
    echo "WebSocket server started
";
};

$ws_worker->onConnect = function($connection) {
    echo "New connection established: {$connection->id}
";
};

$ws_worker->onMessage = function($connection, $data) {
    echo "Received a message from {$connection->id}: $data
";
};

Worker::runAll();

In the above code, we use Workerman's Worker Class to open a WebSocket server and listen on the 8080 port of 127.0.0.1. The count attribute specifies the number of processes started. When a client connects, the onConnect callback function will be triggered; when a client sends a message, the onMessage callback function will be triggered. We can handle client connections and messages in these two callback functions.

3. Implementing an online voting system

In the voting system, we need to support multiple users voting at the same time, and we need to display the voting results in real time. In order to implement such functionality, we need to use PHP's shared memory mechanism and the JSON format to pass data between the client and server.

First, we need to define an associative array $votes on the server side to store the number of votes for each voting option. Each time we receive a voting request from the client, we will add one to the number of votes for the corresponding option, and the number of votes for different options will be stored in different array elements.

<?php
// ...

$votes = [
    'Option 1' => 0,
    'Option 2' => 0,
    'Option 3' => 0,
];

$ws_worker->onMessage = function($connection, $data) use ($votes) {
    $data = json_decode($data, true);
    if (!isset($data['option']) || !isset($votes[$data['option']])) {
        // 投票选项不存在或者为空
        $connection->send(json_encode([
            'code' => 400,
            'message' => 'Invalid option'
        ]));
        return;
    }
    $votes[$data['option']]++;

    // 广播投票结果
    broadcast(json_encode([
        'code' => 200,
        'message' => 'Vote successfully',
        'data' => $votes
    ]));
};

function broadcast($data) {
    global $ws_worker;
    foreach ($ws_worker->connections as $connection) {
        $connection->send($data);
    }
}

In the above code, we use PHP’s global keyword to introduce the $ws_worker object into the broadcast function. In each After voting, the voting results are broadcast to all connected clients in JSON format. In the above code, we also define a broadcast function to send messages to all connected clients.

Next, we need to implement the voting function of the client. In HTML pages, we can create WebSocket objects through JavaScript code for real-time communication with the server.

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket - Online Voting System</title>
</head>
<body>
    <h1 id="Online-Voting-System">Online Voting System</h1>
    <p>Vote for your favorite option:</p>
    <form id="form">
        <input type="radio" name="option" value="Option 1">Option 1<br>
        <input type="radio" name="option" value="Option 2">Option 2<br>
        <input type="radio" name="option" value="Option 3">Option 3<br>
        <input type="submit" value="Vote">
    </form>

    <ul id="result">
        <li>Option 1: <span id="vote1"></span></li>
        <li>Option 2: <span id="vote2"></span></li>
        <li>Option 3: <span id="vote3"></span></li>
    </ul>

    <script type="text/javascript">
        var ws = new WebSocket('ws://127.0.0.1:8080');

        ws.onopen = function() {
            console.log('WebSocket connected');
        }

        ws.onmessage = function(event) {
            var data = JSON.parse(event.data);
            if (data.code === 200) {
                // 投票成功
                updateVotes(data.data);
            } else {
                // 投票失败
                console.error(data.message);
            }
        }

        function updateVotes(votes) {
            document.querySelector('#vote1').innerHTML = votes['Option 1'];
            document.querySelector('#vote2').innerHTML = votes['Option 2'];
            document.querySelector('#vote3').innerHTML = votes['Option 3'];
        }

        var form = document.querySelector('#form');
        form.addEventListener('submit', function(event) {
            event.preventDefault();
            var option = document.querySelector('input[name="option"]:checked');
            if (!option) {
                console.error('Please choose an option');
                return;
            }
            var data = {
                option: option.value
            };
            ws.send(JSON.stringify(data));
            option.checked = false;
        });
    </script>
</body>
</html>

In the above code, we use the onopen and onmessage two callback functions of the WebSocket object, which are used after the connection is established. Output logs and receive messages from the server. In the form, we use the submit event to capture the user's voting behavior and send the voting information to the server through the WebSocket object. Each time we receive voting results from the server, we update the voting data in the HTML page through the updateVotes function.

4. Summary

This article introduces how to use PHP's Workerman framework to implement an online voting system based on the WebSocket protocol, and gives specific code examples. Through studying this article, readers should have a deeper understanding and mastery of the Workerman framework, shared memory mechanism, WebSocket protocol and other knowledge.

The above is the detailed content of Workerman development: How to implement an online voting system based on WebSocket protocol. 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
What Are the Key Features of Workerman's Built-in WebSocket Client?What Are the Key Features of Workerman's Built-in WebSocket Client?Mar 18, 2025 pm 04:20 PM

Workerman's WebSocket client enhances real-time communication with features like asynchronous communication, high performance, scalability, and security, easily integrating with existing systems.

How to Use Workerman for Building Real-Time Collaboration Tools?How to Use Workerman for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:15 PM

The article discusses using Workerman, a high-performance PHP server, to build real-time collaboration tools. It covers installation, server setup, real-time feature implementation, and integration with existing systems, emphasizing Workerman's key f

What Are the Best Ways to Optimize Workerman for Low-Latency Applications?What Are the Best Ways to Optimize Workerman for Low-Latency Applications?Mar 18, 2025 pm 04:14 PM

The article discusses optimizing Workerman for low-latency applications, focusing on asynchronous programming, network configuration, resource management, data transfer minimization, load balancing, and regular updates.

How to Implement Real-Time Data Synchronization with Workerman and MySQL?How to Implement Real-Time Data Synchronization with Workerman and MySQL?Mar 18, 2025 pm 04:13 PM

The article discusses implementing real-time data synchronization using Workerman and MySQL, focusing on setup, best practices, ensuring data consistency, and addressing common challenges.

What Are the Key Considerations for Using Workerman in a Serverless Architecture?What Are the Key Considerations for Using Workerman in a Serverless Architecture?Mar 18, 2025 pm 04:12 PM

The article discusses integrating Workerman into serverless architectures, focusing on scalability, statelessness, cold starts, resource management, and integration complexity. Workerman enhances performance through high concurrency, reduced cold sta

How to Build a High-Performance E-Commerce Platform with Workerman?How to Build a High-Performance E-Commerce Platform with Workerman?Mar 18, 2025 pm 04:11 PM

The article discusses building a high-performance e-commerce platform using Workerman, focusing on its features like WebSocket support and scalability to enhance real-time interactions and efficiency.

What Are the Advanced Features of Workerman's WebSocket Server?What Are the Advanced Features of Workerman's WebSocket Server?Mar 18, 2025 pm 04:08 PM

Workerman's WebSocket server enhances real-time communication with features like scalability, low latency, and security measures against common threats.

How to Use Workerman for Building Real-Time Analytics Dashboards?How to Use Workerman for Building Real-Time Analytics Dashboards?Mar 18, 2025 pm 04:07 PM

The article discusses using Workerman, a high-performance PHP server, to build real-time analytics dashboards. It covers installation, server setup, data processing, and frontend integration with frameworks like React, Vue.js, and Angular. Key featur

See all articles

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools