Table of Contents
Online Voting System
Home PHP Framework Workerman Workerman 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

Nov 07, 2023 am 10:28 AM
websocket workerman online voting system

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

<?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();

Copy after login

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<?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);

    }

}

Copy after login

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

<!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>

Copy after login

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 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

The combination of Java and WebSocket: how to achieve real-time video streaming The combination of Java and WebSocket: how to achieve real-time video streaming Dec 17, 2023 pm 05:50 PM

With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

How to achieve real-time communication using PHP and WebSocket How to achieve real-time communication using PHP and WebSocket Dec 17, 2023 pm 10:24 PM

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages ​​in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

PHP and WebSocket: Best practices for real-time data transfer PHP and WebSocket: Best practices for real-time data transfer Dec 18, 2023 pm 02:10 PM

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use Java and WebSocket to implement real-time stock quotation push How to use Java and WebSocket to implement real-time stock quotation push Dec 17, 2023 pm 09:15 PM

How to use Java and WebSocket to implement real-time stock quotation push Introduction: With the rapid development of the Internet, real-time stock quotation push has become one of the focuses of investors. The traditional stock market push method has problems such as high delay and slow refresh speed. For investors, the inability to obtain the latest stock market information in a timely manner may lead to errors in investment decisions. Real-time stock quotation push based on Java and WebSocket can effectively solve this problem, allowing investors to obtain the latest stock price information as soon as possible.

How does Java Websocket implement online whiteboard function? How does Java Websocket implement online whiteboard function? Dec 17, 2023 pm 10:58 PM

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

See all articles