Home > Backend Development > PHP Tutorial > How to add real-time notifications to your website using PHP and MQTT

How to add real-time notifications to your website using PHP and MQTT

王林
Release: 2023-07-08 20:46:01
Original
1528 people have browsed it

How to add real-time notification functionality to your website using PHP and MQTT

Real-time notification functionality for web applications is becoming more and more popular in modern websites. Real-time notifications can be used for a variety of purposes, such as live chat, real-time comments, and new message alerts. In this article, we will explain how to add real-time notification functionality to your website using PHP and MQTT protocol.

What is the MQTT protocol?

MQTT (Message Queuing Telemetry Transport) is a lightweight message transmission protocol designed to provide efficient instant communication. It is designed for low-bandwidth and unstable network environments, and is very suitable for message transmission for IoT applications.

The MQTT protocol is based on the publish/subscribe model. The client can subscribe to a specific topic (topic). When a new message is published to the topic, the subscriber will receive a notification in real time.

Preparation

Before we begin, we need to ensure that the following conditions are met:

  1. A server running an MQTT broker, such as Mosquitto.
  2. PHP development environment, including installation of Mosquitto MQTT extension.

Installing the Mosquitto MQTT extension can use the pecl command:

pecl install Mosquitto-alpha
Copy after login

Implementing the real-time notification function

In this example, we will create a simple chat application, Users can send messages and receive messages from other users in real time. We will use PHP and MQTT to implement this functionality.

First, we need to create an MQTT client, establish a connection with the MQTT broker, and subscribe to a topic. We will use the phpMQTT library to simplify the implementation of MQTT clients. The phpMQTT library can be installed through the following code:

composer require bluerhinos/phpmqtt
Copy after login

Then, we create a file named chat.php and add the following code:

<?php
require("phpMQTT.php");

$mqtt = new phpMQTT("localhost", 1883, "clientId_" . uniqid());
if ($mqtt->connect()) {
    $mqtt->subscribe("chat_room", 0);
    while ($mqtt->proc()) {
    }
    $mqtt->close();
} else {
    echo "连接MQTT代理失败";
}
Copy after login

In the above code , we first created an mqtt instance and used localhost and 1883 as the host and port of the MQTT broker. Then, we establish a connection to the MQTT broker through the $mqtt->connect() method. If the connection is successful, use $mqtt->subscribe("chat_room", 0) to subscribe to a topic named chat_room. Finally, we use the $mqtt->proc() method to maintain the connection to the MQTT broker.

Next, we create a front-end file named index.html and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>实时聊天</title>
    <meta charset="utf-8">
    <style>
        #chat_log {
            height: 300px;
            overflow-y: scroll;
        }
    </style>
</head>
<body>
    <h1>实时聊天</h1>
    <div id="chat_log"></div>
    <input type="text" id="message" placeholder="请输入消息">
    <button id="send_button">发送</button>
  
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        var clientId = 'web_' + new Date().getTime();
        var mqtt = new Paho.MQTT.Client("localhost", 1883, clientId);
        var topic = "chat_room";
      
        mqtt.onConnectionLost = function(responseObject) {
            console.log('连接丢失');
        };
      
        mqtt.onMessageArrived = function(message) {
            var msg = message.payloadString;
            $("#chat_log").append('<p>' + msg + '</p>');
        };
      
        mqtt.connect({
            onSuccess: function() {
                mqtt.subscribe(topic);
            }
        });
      
        $(document).ready(function() {
            $("#send_button").click(function() {
                var message = $("#message").val();
                mqtt.send(topic, message);
                $("#message").val('');
            });
        });
    </script>
</body>
</html>
Copy after login

In the above code, we first add the following code in The mqtt.onConnectionLost method handles the connection loss event with the MQTT broker. In the mqtt.onMessageArrived method, when we receive a new message, we add the message to the chat history.

By calling the mqtt.connect() method and providing a callback function, subscribe to the chat_room topic after the connection is successful. Then, we use jQuery to implement the message sending function through the $("#send_button").click method when the page loads.

Finally, we open the index.html file in the browser and you can see the chat interface.

Summary

This article introduces how to use PHP and MQTT protocol to add real-time notification functionality to the website. We have created a simple chat application by using phpMQTT library where users can send messages and receive messages from other users in real time. Through this example, we can see how to use the MQTT protocol to achieve efficient instant communication to meet the needs of modern websites.

The above is the detailed content of How to add real-time notifications to your website using PHP and MQTT. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template