Home PHP Framework Swoole How to use Swoole to build a high-performance WebSocket server

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

Jun 13, 2023 pm 11:59 PM
websocket high performance swoole

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 the php --ri swoole command 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:

<?php
$server = new swoole_websocket_server("0.0.0.0", 9502);

$server->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 the SwooleCoroutineun function 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:

<?php
use SwooleCoroutine;
Coun(function () {
    $server = new swoole_websocket_server("0.0.0.0", 9502);

    $server->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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and WebSocket: Best practices for real-time data transfer PHP and WebSocket: Best practices for real-time data transfer Dec 18, 2023 pm 02:10 PM

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

How to use swoole coroutine in laravel How to use swoole coroutine in laravel Apr 09, 2024 pm 06:48 PM

Using Swoole coroutines in Laravel can process a large number of requests concurrently. The advantages include: Concurrent processing: allows multiple requests to be processed at the same time. High performance: Based on the Linux epoll event mechanism, it processes requests efficiently. Low resource consumption: requires fewer server resources. Easy to integrate: Seamless integration with Laravel framework, simple to use.

SSE and WebSocket SSE and WebSocket Apr 17, 2024 pm 02:18 PM

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration

golang WebSocket programming tips: handling concurrent connections golang WebSocket programming tips: handling concurrent connections Dec 18, 2023 am 10:54 AM

Golang is a powerful programming language, and its use in WebSocket programming is increasingly valued by developers. WebSocket is a TCP-based protocol that allows two-way communication between client and server. In this article, we will introduce how to use Golang to write an efficient WebSocket server that handles multiple concurrent connections at the same time. Before introducing the techniques, let's first learn what WebSocket is. Introduction to WebSocketWeb

How to use WebSocket for file transfer in golang How to use WebSocket for file transfer in golang Dec 18, 2023 am 09:06 AM

How to use WebSocket for file transfer in golang WebSocket is a network protocol that supports two-way communication and can establish a persistent connection between the browser and the server. In golang, we can use the third-party library gorilla/websocket to implement WebSocket functionality. This article will introduce how to use golang and gorilla/websocket libraries for file transfer. First, we need to install gorilla

Which one is better, swoole or workerman? Which one is better, swoole or workerman? Apr 09, 2024 pm 07:00 PM

Swoole and Workerman are both high-performance PHP server frameworks. Known for its asynchronous processing, excellent performance, and scalability, Swoole is suitable for projects that need to handle a large number of concurrent requests and high throughput. Workerman offers the flexibility of both asynchronous and synchronous modes, with an intuitive API that is better suited for ease of use and projects that handle lower concurrency volumes.

How does swoole_process allow users to switch? How does swoole_process allow users to switch? Apr 09, 2024 pm 06:21 PM

Swoole Process allows users to switch. The specific steps are: create a process; set the process user; start the process.

PHP Websocket development guide to implement real-time translation function PHP Websocket development guide to implement real-time translation function Dec 18, 2023 pm 05:52 PM

PHP Websocket Development Guide: Implementing Real-time Translation Function Introduction: With the development of the Internet, real-time communication is becoming more and more important in various application scenarios. As an emerging communication protocol, Websocket provides good support for real-time communication. This article will take you through a detailed understanding of how to use PHP to develop Websocket applications, and combine the real-time translation function to demonstrate its specific application. 1. What is the Websocket protocol? The Websocket protocol is a

See all articles