Table of Contents
实时在线投票系统
请选择您的投票选项:
当前投票结果:
Home Web Front-end JS Tutorial How to implement a real-time online voting system using JavaScript and WebSocket

How to implement a real-time online voting system using JavaScript and WebSocket

Dec 18, 2023 pm 04:27 PM
javascript websocket Live online voting

How to implement a real-time online voting system using JavaScript and WebSocket

How to use JavaScript and WebSocket to implement a real-time online voting system

Introduction:
With the rapid development of the Internet, real-time online voting systems have become an important part of various activities and A very common form of election. Using JavaScript and WebSocket technology to implement a real-time online voting system has the advantages of flexibility and ease of use. This article will introduce in detail how to use JavaScript and WebSocket to implement a simple real-time online voting system, and provide corresponding code examples.

1. Basic architecture of real-time online voting system
The basic architecture of real-time online voting system generally includes the following parts:

  1. Front-end HTML page: used to display voting options and a page that updates voting results in real time.
  2. Backend server: used to process voting requests sent by clients and send voting results to all connected clients in real time.
  3. WebSocket connection: used to achieve real-time two-way communication and update the page in time when the votes change.

2. Design and implementation of front-end HTML page

  1. Page layout:
    First, we need to design a simple page layout, including voting options and real-time voting The display area of ​​the results. Page layout can be implemented using HTML and CSS, as shown below:

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

<!DOCTYPE html>

<html>

<head>

  <title>实时在线投票系统</title>

  <style>

    /* 页面布局样式 */

    /* ... */

  </style>

</head>

<body>

  <h1 id="实时在线投票系统">实时在线投票系统</h1>

  <div id="options">

    <h2 id="请选择您的投票选项">请选择您的投票选项:</h2>

    <ul>

      <li><button onclick="vote(1)">选项1</button></li>

      <li><button onclick="vote(2)">选项2</button></li>

      <li><button onclick="vote(3)">选项3</button></li>

    </ul>

  </div>

  <div id="result">

    <h2 id="当前投票结果">当前投票结果:</h2>

    <p>选项1: <span id="count1">0</span> 票</p>

    <p>选项2: <span id="count2">0</span> 票</p>

    <p>选项3: <span id="count3">0</span> 票</p>

  </div>

   

  <script src="websocket.js"></script>

  <script>

    // 实时更新投票结果

    function updateResult(counts) {

      document.getElementById('count1').innerText = counts[1];

      document.getElementById('count2').innerText = counts[2];

      document.getElementById('count3').innerText = counts[3];

    }

   

    // 发送投票请求

    function vote(option) {

      // 发送投票请求给后端

      sendVoteRequest(option);

    }

  </script>

</body>

</html>

Copy after login
  1. JavaScript code:
    The above HTML code contains some JavaScript code, which is mainly responsible for implementing voting functions and communicates with the backend server. We need to write a JavaScript file named websocket.js to handle communication with the WebSocket server, as shown below:

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

// 创建WebSocket连接

const socket = new WebSocket('ws://localhost:8000');

 

// 连接建立时触发

socket.onopen = function(event) {

  console.log('WebSocket连接已建立');

};

 

// 接收投票结果

socket.onmessage = function(event) {

  const counts = JSON.parse(event.data);

  updateResult(counts);

};

 

// 连接关闭时触发

socket.onclose = function(event) {

  console.log('WebSocket连接已关闭');

};

 

// 向服务器发送投票请求

function sendVoteRequest(option) {

  const message = {

    type: 'vote',

    option: option

  };

  socket.send(JSON.stringify(message));

}

Copy after login

3. Construction of the back-end server and Implementation
The back-end server is built using Node.js and WebSocket libraries. The code examples are 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

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

const WebSocket = require('ws');

 

// 创建WebSocket服务器

const wss = new WebSocket.Server({ port: 8000 });

 

// 记录投票结果

let counts = {

  1: 0,

  2: 0,

  3: 0

};

 

// 处理客户端连接请求

wss.on('connection', function(ws) {

  console.log('客户端已连接');

 

  // 发送当前投票结果给客户端

  ws.send(JSON.stringify(counts));

 

  // 处理客户端发送的消息

  ws.on('message', function(message) {

    const data = JSON.parse(message);

 

    // 根据投票选项更新投票结果

    if (data.type === 'vote') {

      counts[data.option] += 1;

 

      // 发送更新后的投票结果给所有连接的客户端

      wss.clients.forEach(function(client) {

        client.send(JSON.stringify(counts));

      });

    }

  });

 

  // 连接关闭时触发

  ws.on('close', function() {

    console.log('客户端已断开连接');

  });

});

 

console.log('WebSocket服务器已启动');

Copy after login

4. Running and testing

  1. Install Node.js and WebSocket library:
    Before running the above code, you need to install Node.js and install the WebSocket library through npm. Open the terminal and execute the following command:

    1

    $ npm install websocket

    Copy after login
  2. Start the backend server:
    In the terminal, enter the directory where the above back-end server code is saved, and execute the following command to start the back-end server:

    1

    $ node server.js

    Copy after login
  3. Open the front-end page in the browser:
    Browse Open the file containing the above front-end HTML page in your browser to start voting.
  4. Summary:
    Through the above steps, we successfully implemented a simple real-time online voting system using JavaScript and WebSocket. Based on this system, we can further expand the functions and implement more complex voting systems. By flexibly using JavaScript and WebSocket technology, we can build various real-time applications on the Internet.

    The above is the detailed content of How to implement a real-time online voting system using JavaScript and WebSocket. 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)

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

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

SSE and WebSocket SSE and WebSocket Apr 17, 2024 pm 02:18 PM

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration

golang WebSocket programming tips: handling concurrent connections golang WebSocket programming tips: handling concurrent connections Dec 18, 2023 am 10:54 AM

Golang is a powerful programming language, and its use in WebSocket programming is increasingly valued by developers. WebSocket is a TCP-based protocol that allows two-way communication between client and server. In this article, we will introduce how to use Golang to write an efficient WebSocket server that handles multiple concurrent connections at the same time. Before introducing the techniques, let's first learn what WebSocket is. Introduction to WebSocketWeb

See all articles