Table of Contents
健身房预约系统
可预约时间段:
Home Web Front-end JS Tutorial How to implement an online reservation system using WebSocket and JavaScript

How to implement an online reservation system using WebSocket and JavaScript

Dec 17, 2023 am 09:39 AM
javascript websocket Online Reservations

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);
});
Copy after login
  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));
}
Copy after login
  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;
}
Copy after login
  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 id="健身房预约系统">健身房预约系统</h1>
  
  <h2 id="可预约时间段">可预约时间段:</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>
Copy after login

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));
});
Copy after login
Copy after login
  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));
});
Copy after login
Copy after login

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