Home  >  Article  >  Web Front-end  >  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

PHPz
PHPzOriginal
2023-12-18 16:27:391103browse

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:
<!DOCTYPE html>
<html>
<head>
  <title>实时在线投票系统</title>
  <style>
    /* 页面布局样式 */
    /* ... */
  </style>
</head>
<body>
  <h1>实时在线投票系统</h1>
  <div id="options">
    <h2>请选择您的投票选项:</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>当前投票结果:</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>
  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:
// 创建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));
}

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:

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服务器已启动');

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:

    $ npm install websocket
  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:

    $ node server.js
  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.

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