In the Internet era, chat rooms have become an important place for people to communicate and socialize. The emergence of WebSocket technology has made real-time communication smoother and more stable. Today, we introduce how to use the Swoole framework to quickly build a chat room based on WebSocket.
Swoole is a high-performance PHP coroutine network communication framework, written in C language, integrating asynchronous IO, coroutine, network communication and other functions, allowing PHP code to be processed as efficiently as Node.js Event-driven asynchronous concurrent programming. It can be said that Swoole is an important tool for developing high-concurrency network applications.
Below, we will introduce step by step how to use Swoole to implement a chat room based on WebSocket and support multi-person online chat.
Before you start, you need to make sure you have installed the Swoole extension and enabled WebSocket support.
The installation method is as follows:
pecl install swoole
Or compile and install:
wget https://pecl.php.net/get/swoole-{version}.tgz tar xzvf swoole-{version}.tgz cd swoole-{version} phpize ./configure --enable-async-redis --enable-coroutine --enable-openssl --enable-http2 --enable-sockets make && make install
If Docker is used, you can add the following statements in the Dockerfile:
RUN pecl install swoole && docker-php-ext-enable swoole && docker-php-ext-install pcntl
First, we need to write a page for sending messages to the chat room. The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>WebSocket ChatRoom Demo</title> <style> * { margin: 0; padding: 0; } .container { margin: 30px auto; width: 800px; height: 600px; border: 1px solid #aaa; border-radius: 5px; overflow: hidden; } .message-box { width: 800px; height: 500px; border-bottom: 1px solid #aaa; overflow-y: scroll; } .input-box { width: 800px; height: 100px; border-top: 1px solid #aaa; } .input-text { width: 600px; height: 80px; margin: 10px; padding: 10px; font-size: 20px; border-radius: 5px; border: 1px solid #aaa; outline: none; } .send-btn { width: 100px; height: 100%; margin: 0 10px; background-color: #4CAF50; border: none; color: white; font-size: 18px; border-radius: 5px; cursor: pointer; } </style> </head> <body> <div class="container"> <div class="message-box"></div> <div class="input-box"> <textarea class="input-text"></textarea> <button class="send-btn">Send</button> </div> </div> <script> // 初始化WebSocket let socket = new WebSocket('ws://localhost:9502'); // 监听连接成功事件 socket.onopen = function (event) { console.log('WebSocket connection established.'); } // 监听服务端发送的消息 socket.onmessage = function (event) { let message_box = document.querySelector('.message-box'); message_box.innerHTML += `<p>${event.data}</p>`; message_box.scrollTop = message_box.scrollHeight; } // 监听连接关闭事件 socket.onclose = function (event) { console.log('WebSocket connection closed.'); } // 发送消息 let send_btn = document.querySelector('.send-btn'); let input_text = document.querySelector('.input-text'); send_btn.addEventListener('click', function (event) { if (input_text.value.trim() == '') return; socket.send(input_text.value); input_text.value = ''; }); </script> </body> </html>
In this code, we divide the chat room page into two parts: the message display box and the message input box. At the same time, the related logic of WebSocket connection and message sending is defined.
It should be noted that when deploying in a local environment, the address of WebSocket
needs to be modified to the local IP address instead of localhost
. If you want to use an online environment, you need to change the WebSocket
address to the server's public IP.
Next, we write the server-side code. Through the class library provided by Swoole, we can easily create a WebSocket server. The code is as follows:
<?php // 创建WebSocket服务器 $server = new SwooleWebsocketServer("0.0.0.0", 9502); // 监听WebSocket连接打开事件 $server->on('open', function (SwooleWebsocketServer $server, $request) { echo "connection open: {$request->fd} "; }); // 监听WebSocket消息事件 $server->on('message', function (SwooleWebsocketServer $server, $frame) { echo "received message: {$frame->data} "; // 广播消息 foreach ($server->connections as $fd) { $server->push($fd, $frame->data); } }); // 监听WebSocket连接关闭事件 $server->on('close', function (SwooleWebsocketServer $server, $fd) { echo "connection close: {$fd} "; }); // 启动WebSocket服务器 $server->start();
First, we create a WebSocket server and bind it to the address 0.0.0.0:9502
to wait for client connections. The three events of WebSocket connection opening, message, and connection closing are monitored through the on
method, and the processing logic for these three events has been implemented.
In the open
event, we use the client fd recorded by Swoole to output it to the console.
In the message
event, we obtain the information from the client, use echo
to output it to the console, and pass foreach
Traverse the clients that have established connections and broadcast the message to all clients.
In the close
event, we again use the client fd recorded by Swoole and output it to the console.
Finally, we use the start
method to start the WebSocket server.
So far, we have implemented a multi-person online chat room based on WebSocket. In the client page, you can send any message, and the message will be broadcast to all online clients for display.
Through the Swoole framework, we can easily create an efficient WebSocket server, which provides a convenient means to achieve high performance, low latency, and reliable real-time communication.
The above is the detailed content of Swoole in action: quickly create a chat room based on WebSocket. For more information, please follow other related articles on the PHP Chinese website!