Home > Article > PHP Framework > ThinkPHP6 Chat Room Development Guide: Implementing Real-time Communication Functions
ThinkPHP6 Chat Room Development Guide: Implementing Real-time Communication Function
Introduction:
With the rapid development of the Internet, the demand for real-time communication is also increasing. As a common method of real-time communication, chat rooms have received widespread attention and use. This article will provide you with a simple and fast method to implement real-time communication functions by using the ThinkPHP6 framework.
1. Environment configuration:
Before we start, we need to configure the development environment. Make sure you have PHP and ThinkPHP6 framework installed. At the same time, this article will use the MySQL database, so you also need to ensure that you have installed and configured MySQL correctly.
2. Create database and tables:
We first create a database named chatroom. Then create a table named messages to store chat messages. The table structure is as follows:
CREATE TABLE `messages` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `content` text COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
3. Write controllers and views:
Next, we need to create a Chatroom controller to handle chat room-related logic. Create Chatroom.php in the app/controller directory and add the following code:
<?php namespace appcontroller; use thinkacadeView; use GatewayWorkerLibGateway; class Chatroom { public function index() { return View::fetch('index'); } public function sendMessage() { $content = input('post.content'); $data = [ 'content' => $content, 'created_at' => date('Y-m-d H:i:s') ]; hinkacadeDb::name('messages')->insert($data); Gateway::sendToAll(json_encode($data)); } }
Create index.html in the app/view directory and add the following code:
<!DOCTYPE html> <html> <head> <title>聊天室</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <div> <textarea id="message" style="width: 300px; height: 100px;"></textarea> <button onclick="sendMessage()">发送</button> </div> <div id="chatContent"></div> </body> <script> var websocket = new WebSocket('ws://localhost:8282'); websocket.onopen = function () { console.log('连接成功'); }; websocket.onmessage = function (evt) { var message = JSON.parse(evt.data); $('#chatContent').append('<p>' + message.content + ' - ' + message.created_at + '</p>'); }; websocket.onerror = function () { console.log('连接失败'); }; websocket.onclose = function () { console.log('断开连接'); }; function sendMessage() { var content = $('#message').val(); $.ajax({ type: 'POST', url: '<?php echo url("Chatroom/sendMessage"); ?>', data: {content: content}, success: function () { $('#message').val(''); }, error: function () { alert('发送失败'); } }); } </script> </html>
4. Start WebSocket Service:
ThinkPHP6 does not integrate the WebSocket service by default. We need to use the GatewayWorker extension to achieve it. First, we need to install the GatewayWorker extension:
composer require workerman/gatewayworker
Next, create start.php in the project root directory and add the following code:
<?php use thinkacadeDb; use WorkermanWorker; use GatewayWorkerGateway; require __DIR__ . '/vendor/autoload.php'; $worker = new Worker('websocket://0.0.0.0:8282'); $worker->name = 'ChatroomGateway'; $worker->count = 1; $worker->onWorkerStart = function () { Gateway::$registerAddress = '127.0.0.1:1238'; Gateway::onConnect(function ($connection) { $messages = Db::name('messages')->select(); Gateway::sendToCurrentClient(json_encode($messages)); }); Gateway::onMessage(function ($connection, $data) { Gateway::sendToAll($data); }); }; Worker::runAll();
Then execute the following command in the command line to start WebSocket Service:
php start.php start
5. Completion:
Now, we can use the chat room by accessing http://localhost/chatroom/index. After entering the message and clicking Send, you can send and receive messages in real time.
Conclusion:
Through the guidance of this article, we successfully implemented a simple chat room using the ThinkPHP6 framework and GatewayWorker extension. I hope this article can provide readers with some useful references to help quickly implement real-time communication functions. However, it should be noted that this article only provides a simple example. In actual projects, it needs to be expanded and optimized according to specific needs.
The above is the detailed content of ThinkPHP6 Chat Room Development Guide: Implementing Real-time Communication Functions. For more information, please follow other related articles on the PHP Chinese website!