Home  >  Article  >  Web Front-end  >  How to implement an online reservation system using WebSocket and JavaScript

How to implement an online reservation system using WebSocket and JavaScript

WBOY
WBOYOriginal
2023-12-17 09:39:02636browse

How to implement an online reservation system using WebSocket and JavaScript

How to use WebSocket and JavaScript to implement an online reservation system

In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples.

1. What is WebSocket
WebSocket is a protocol for full-duplex communication on a single TCP connection. It can establish a persistent connection between the browser and the server to achieve real-time communication. Compared with traditional HTTP requests, WebSocket can send and receive data more quickly.

2. Sample Requirements Analysis
Let’s assume that we are developing an online reservation system for a gym. Users can select a suitable time period to make an appointment through the website, and the system will promptly feedback the status of the selected time period to the user.

Based on the above requirements, we can divide the system into two roles: client and server. The client provides a user-operable interface, and the server is responsible for processing the user's reservation request and pushing the real-time reservation status to the client.

3. Client implementation

  1. Establishing WebSocket connection
    In the JavaScript code of the client, we need to use new WebSocket(url) to establish the The server's WebSocket connection. Among them, url is the WebSocket address of the server.
const socket = new WebSocket("ws://localhost:8080/ws");
socket.addEventListener("open", (event) => {
  console.log("WebSocket连接已建立。");
});

socket.addEventListener("message", (event) => {
  const message = JSON.parse(event.data);
  console.log("收到消息:", message);
});
  1. Processing user reservation requests
    When the user selects the appropriate time period on the web page and clicks the reservation button, we need to send the user's reservation request to the server.
function bookTimeslot(timeslot) {
  const message = {
    action: "book",
    timeslot: timeslot
  };
  socket.send(JSON.stringify(message));
}
  1. Update reservation status
    When the server has a new reservation status, we need to update the status display on the web page.
function updateTimeslotStatus(timeslot, status) {
  const element = document.getElementById(timeslot);
  element.innerHTML = status;
}
  1. Complete client code example
<!DOCTYPE html>
<html>
<head>
  <script>
    const socket = new WebSocket("ws://localhost:8080/ws");
    socket.addEventListener("open", (event) => {
      console.log("WebSocket连接已建立。");
    });

    socket.addEventListener("message", (event) => {
      const message = JSON.parse(event.data);
      console.log("收到消息:", message);
      updateTimeslotStatus(message.timeslot, message.status);
    });

    function bookTimeslot(timeslot) {
      const message = {
        action: "book",
        timeslot: timeslot
      };
      socket.send(JSON.stringify(message));
    }

    function updateTimeslotStatus(timeslot, status) {
      const element = document.getElementById(timeslot);
      element.innerHTML = status;
    }
  </script>
</head>
<body>
  <h1>健身房预约系统</h1>
  
  <h2>可预约时间段:</h2>
  <ul>
    <li id="timeslot1"><button onclick="bookTimeslot('timeslot1')">8:00-9:00</button></li>
    <li id="timeslot2"><button onclick="bookTimeslot('timeslot2')">9:00-10:00</button></li>
    <li id="timeslot3"><button onclick="bookTimeslot('timeslot3')">10:00-11:00</button></li>
  </ul>
</body>
</html>

4. Server implementation
On the server side, we need to process the reservation request sent by the client, And update the reservation status according to the system status. At the same time, the server also needs to send the new reservation status to the client.

  1. Create WebSocket server
    In the Node.js environment, we can use the ws module to create a WebSocket server.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

const timeslots = {
  timeslot1: "可预约",
  timeslot2: "可预约",
  timeslot3: "可预约"
};

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    const data = JSON.parse(message);
    if (data.action === "book") {
      if (timeslots[data.timeslot] === "可预约") {
        timeslots[data.timeslot] = "已预约";
        ws.send(JSON.stringify({
          timeslot: data.timeslot,
          status: timeslots[data.timeslot]
        }));
      }
    }
  });

  ws.send(JSON.stringify(timeslots));
});
  1. Complete server code example
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

const timeslots = {
  timeslot1: "可预约",
  timeslot2: "可预约",
  timeslot3: "可预约"
};

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    const data = JSON.parse(message);
    if (data.action === "book") {
      if (timeslots[data.timeslot] === "可预约") {
        timeslots[data.timeslot] = "已预约";
        ws.send(JSON.stringify({
          timeslot: data.timeslot,
          status: timeslots[data.timeslot]
        }));
      }
    }
  });

  ws.send(JSON.stringify(timeslots));
});

5. Summary
This article introduces how to use WebSocket and JavaScript to implement an online reservation system, and Complete client-side and server-side code examples are provided. By using WebSocket to achieve real-time communication, we can implement a more efficient and real-time online reservation system. It can also be applied in other scenarios that require real-time communication. I hope this article will be helpful to your project development!

The above is the detailed content of How to implement an online reservation system using WebSocket and JavaScript. 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