With the development of the Internet, real-time communication has become more and more important. Whether it is online customer service or real-time interaction in games, real-time communication support is required. As one of the mainstream languages of Web development, PHP language actually has more and more real-time communication methods. Among them, using Pusher technology, real-time communication functions can be realized quickly and conveniently.
What is Pusher?
Pusher is a real-time messaging service that allows applications to easily implement real-time communication functions without building their own server. It is based on the WebSockets protocol and has the advantages of strong reliability and stability, ease of use and high development efficiency. Moreover, Pusher also provides a variety of different SDKs, including PHP, Javascript, Ruby and other languages. These SDKs allow developers to quickly integrate Pusher services in their applications to achieve real-time communication functions.
How to use Pusher?
Before using Pusher, we need to register a Pusher account and create an application. Then, we need to generate an App Key, App Secret and App ID in the application and add this information to our application.
Next, we need to install Pusher PHP SDK, which can be installed through Composer:
composer require pusher/pusher-php-server "^4.0"
After the installation is completed, we can start writing code:
<?php // 引入Pusher SDK require __DIR__ . '/vendor/autoload.php'; // 初始化Pusher实例 $options = array( 'cluster' => 'YOUR_CLUSTER', 'useTLS' => true ); $pusher = new PusherPusher( 'APP_KEY', 'APP_SECRET', 'APP_ID', $options ); // 发送消息 $pusher->trigger('channel_name', 'event_name', array('message' => 'hello world'));
The above code demonstration How to use Pusher, the content that needs to be replaced is:
This PHP script will push a JSON data packet with the "message" attribute to the channel named "channel_name". The data packet contains the message "hello world".
Of course, in actual applications, it is impossible for us to only send messages to Pusher in this way. Below, we will introduce in detail how to use Pusher in practical applications.
Practical combat: a real-time chat room
Next, we will use Pusher to build a real-time chat room to realize the real-time chat function between users.
Step One: Preparation
First, we need to create a new application in Pusher. Log in to Pusher's official website, click the "CREATE NEW APP" button, fill in the basic information and create the application as prompted.
Then, we need to find APP_KEY, APP_SECRET and APP_ID under the "Keys" tab of the application settings, and keep this information properly.
Next, we need to set up a web server to run our PHP script. Since we need to push messages in real time, we cannot use the traditional Apache or Nginx server and need to use a server that supports the WebSocket protocol. It is recommended to use the Ratchet PHP library as the WebSocket server, which can be installed through Composer:
composer require cboden/ratchet
Step 2: Build a basic interface
Before starting to write PHP code, we need to build a basic interface Chat room interface. The interface needs to contain the following elements:
Here, we use relatively simple HTML and JavaScript code to implement this interface.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>实时聊天室</title> </head> <body> <ul id="messages"></ul> <form id="chat-form"> <input type="text" id="message-input"/> <button type="submit">发送</button> </form> <script src="https://js.pusher.com/7.0/pusher.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> // 初始化Pusher客户端 const pusher = new Pusher('APP_KEY', { cluster: 'YOUR_CLUSTER', encrypted: true }); // 订阅频道 const channel = pusher.subscribe('chat-channel'); // 处理消息 channel.bind('chat-message', function(data) { $('#messages').append('<li>' + data.message + '</li>'); }); // 发送消息 $('#chat-form').submit(function(e) { e.preventDefault(); const message = $('#message-input').val(); $('#message-input').val(''); $.post('/send-message.php', {message: message}); }); </script> </body> </html>
In the above code, we introduced the Pusher client and jQuery library, and defined a Pusher client instance. Then, we subscribed to the Pusher channel named "chat-channel" and defined an event handler function to write the message to the message list when the "chat-message" event is received in this channel. At the same time, we also defined a form submission event processing function. When the user clicks the send button, the form data will be POSTed to the /send-message.php file.
Step 3: Send and receive messages
Now, we need to implement the code in the /send-message.php file so that the form data can be sent to the Pusher server correctly. The complete /send-message.php code is as follows:
<?php // 引入Pusher SDK require __DIR__ . '/vendor/autoload.php'; // 初始化Pusher实例 $options = array( 'cluster' => 'YOUR_CLUSTER', 'useTLS' => true ); $pusher = new PusherPusher( 'APP_KEY', 'APP_SECRET', 'APP_ID', $options ); // 获取消息内容 $message = $_POST['message']; // 将消息推送到Pusher服务器中 $pusher->trigger('chat-channel', 'chat-message', array('message' => $message));
In the above code, we first introduced the Pusher SDK and initialized a Pusher instance. Then, we push the message to the Pusher channel named "chat-channel" based on the data submitted by the form, and specify the event name and message content.
In this way, when the user enters a message in the chat room and clicks the "Send" button, the message will be POSTed to the /send-message.php file, and then the PHP code will push the message to the Pusher server . At this time, the Pusher server will broadcast the message to all clients that have subscribed to the "chat-channel" to complete the entire message sending and receiving process.
Conclusion
Using Pusher technology to implement real-time communication functions can greatly simplify the implementation difficulty and improve development efficiency. Through the above example demonstration, we can see that it is very convenient to use Pusher technology to build a real-time chat room in practice.
Of course, Pusher is not limited to chat room application scenarios, but can be used in countless scenarios, such as real-time games, Internet of Things, real-time data monitoring and other scenarios that can be implemented using Pusher technology. If you also need to implement real-time communication functions, you can try using Pusher to quickly implement related functions.
The above is the detailed content of Real-time communication using PHP and Pusher. For more information, please follow other related articles on the PHP Chinese website!