Home> PHP Framework> Swoole> body text

How to use Swoole to build a high-performance WebSocket server

WBOY
Release: 2023-06-13 23:59:20
Original
1356 people have browsed it

In recent years, WebSocket technology has become more and more popular in Internet development, especially in the fields of real-time communication, online games, push messages, etc. As a high-performance, asynchronous PHP extension, Swoole can help developers easily build high-performance WebSocket servers. This article will introduce how to use Swoole to build a high-performance WebSocket server.

1. Install Swoole

Swoole supports PHP 5.3~7.4 versions and can be installed through pecl or source code. The following takes source code installation as an example:

First download the Swoole installation package, then unzip it into the directory and execute the following command:

phpize ./configure make make install
Copy after login

After the installation is completed, add the following configuration items to php.ini to enable it Swoole extension:

extension=swoole
Copy after login

After the installation is complete, use thephp --ri swoolecommand to query the basic information of Swoole.

2. Create a WebSocket server

Let’s build a simple WebSocket server. First create a server.php file in the project root directory and enter the following code:

on("open", function (swoole_websocket_server $server, swoole_http_request $request) { echo "client {$request->fd} connected "; }); $server->on("message", function (swoole_websocket_server $server, $frame) { echo "received message: {$frame->data} "; }); $server->on("close", function (swoole_websocket_server $server, $fd) { echo "client {$fd} closed "; }); $server->start();
Copy after login

In the above code, we first created a swoole_websocket_server instance and set the listening address to 0.0.0.0 and the port to 9502. Then the three events of open, message, and close are monitored respectively, and the corresponding event processing functions are triggered when the client connection is established, a message is received, and the connection is closed.

Next, run the following command on the console to start the WebSocket server:

php server.php
Copy after login

If everything is normal, you can see output similar to the following:

2019-06-17 10:51:17|INFO|Server Start: 0.0.0.0:9502
Copy after login

3. Test the WebSocket server

After starting the WebSocket server, you can use WebSocket plug-in tools commonly used by front-end developers, such as Firefox's Simple WebSocket Client plug-in or Chrome's WebSocket Client plug-in to test whether the server is working properly.

Take Firefox Simple WebSocket Client as an example. After opening the plug-in, enter ws://127.0.0.1:9502 and click the Connect button. At this time we will find that the "client 1 connected" log is output on the server console, which indicates that the WebSocket client has successfully connected to the server.

We can enter the test content in the sending area of the plug-in, for example, enter "hello" and click the send button. You can see the corresponding "received message: hello" log on the console, indicating that the server has successfully received it. Message sent by WebSocket client.

4. Improve performance

In large traffic scenarios, the performance of the WebSocket server is very critical. Swoole provides multiple mechanisms to improve the performance of WebSocket servers.

  1. Open the coroutine

By calling theSwooleCoroutineunfunction in the code to open the coroutine, multiple coroutines can be executed concurrently and improve the server's performance. throughput.

For example, modify the code in server.php:

on("open", function (swoole_websocket_server $server, swoole_http_request $request) { echo "client {$request->fd} connected "; }); $server->on("message", function (swoole_websocket_server $server, $frame) { echo "received message: {$frame->data} "; }); $server->on("close", function (swoole_websocket_server $server, $fd) { echo "client {$fd} closed "; }); $server->start(); });
Copy after login
  1. Set the number of workers

When starting the server, you can set the number of workers. Improve the server's concurrent processing capabilities. The number of workers can be set in the following ways:

$server->set([ 'worker_num' => 4, // 工作进程数量 ]);
Copy after login

Under the coroutine, the number of workers needs to be set within the run function.

  1. Use asynchronous MySQL

If the WebSocket server needs to operate the database, you can use Swoole's asynchronous MySQL client to avoid blocking caused by database operations, thereby improving server performance .

For example, the sample code for using Swoole asynchronous MySQL client to obtain a record is as follows:

$db = new SwooleCoroutineMySQL(); $db->connect([ 'host' => 'localhost', 'port' => 3306, 'user' => 'root', 'password' => '', 'database' => 'test', ]); $res = $db->query('SELECT * FROM users WHERE id = 1');
Copy after login

The above is the basic process of how to use Swoole to build a high-performance WebSocket server. By using the asynchronous support, multi-process, coroutine and other advantages provided by Swoole, the performance of the WebSocket server can be greatly improved, making the application more stable and efficient.

The above is the detailed content of How to use Swoole to build a high-performance WebSocket server. 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!