<h2 align=center>
<img width="200" height="120" alt="Swoole Logo" src="docs/swoole-logo.svg" /> <br />
Swoole is an event-driven, asynchronous, coroutine-based concurrency library with high performance for PHP.
</h2>
[](https://github.com/swoole/swoole-src/actions?query=workflow%3Alib-swoole)
[](https://github.com/swoole/swoole-src/actions?query=workflow%3Aext-swoole)
[](https://github.com/swoole/swoole-src/actions?query=workflow%3Atest-linux)
[](https://github.com/swoole/swoole-src/actions/workflows/framework.yml)
[](https://codecov.io/gh/swoole/swoole-src)
[](https://twitter.com/phpswoole)
[](https://discord.swoole.dev)
[](https://github.com/swoole/swoole-src/releases/)
[](https://github.com/swoole/swoole-src/blob/master/LICENSE)
[](https://scan.coverity.com/projects/swoole-swoole-src)
## âï¸ Quick Start
Run Swoole program by [Docker](https://github.com/swoole/docker-swoole)
```bash
docker run --rm phpswoole/swoole "php --ri swoole"
```
> For details on how to use it, see: [How to Use This Image](https://github.com/swoole/docker-swoole#how-to-use-this-image).
### HTTP Service
```php
$http = new Swoole\Http\Server('127.0.0.1', 9501);
$http->set(['hook_flags' => SWOOLE_HOOK_ALL]);
$http->on('request', function ($request, $response) {
$result = [];
Co::join([
go(function () use (&$result) {
$result['google'] = file_get_contents("https://www.google.com/");
}),
go(function () use (&$result) {
$result['taobao'] = file_get_contents("https://www.taobao.com/");
})
]);
$response->end(json_encode($result));
});
$http->start();
```
### Concurrency
```php
Co\run(function() {
Co\go(function() {
while(1) {
sleep(1);
$fp = stream_socket_client("tcp://127.0.0.1:8000", $errno, $errstr, 30);
echo fread($fp, 8192), PHP_EOL;
}
});
Co\go(function() {
$fp = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
while(1) {
$conn = stream_socket_accept($fp);
fwrite($conn, 'The local time is ' . date('n/j/Y g:i a'));
}
});
Co\go(function() {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
while(true) {
$redis->subscribe(['test'], function ($instance, $channelName, $message) {
echo 'New redis message: '.$channelName, "==>", $message, PHP_EOL;
});
}
});
Co\go(function() {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$count = 0;
while(true) {
sleep(2);
$redis->publish('test','hello, world, count='.$count++);
}
});
});
```
## Runtime Hook
**Swoole hooks the blocking io function of PHP at the `bottom layer` and `automatically` converts it to a non-blocking function, so that these functions can be called concurrently in coroutines.**
### Supported extension/functions
* `ext-curl` (Support `symfony` and `guzzle`)
* `ext-redis`
* `ext-mysqli`
* `ext-pdo_mysql`
* `ext-pdo_pgsql`
* `ext-pdo_sqlite`
* `ext-pdo_oracle`
* `ext-pdo_odbc`
* `stream functions` (e.g. `stream_socket_client`/`stream_socket_server`), Supports `TCP`/`UDP`/`UDG`/`Unix`/`SSL/TLS`/`FileSystem API`/`Pipe`
* `ext-sockets`
* `ext-soap`
* `sleep`/`usleep`/`time_sleep_until`
* `proc_open`
* `gethostbyname`/`shell_exec`/`exec`
* `fread`/`fopen`/`fsockopen`/`fwrite`/`flock`
## ð Develop & Discussion
+ __IDE Helper & API__: <https://github.com/swoole/ide-helper>
+ __Twitter__: <https://twitter.com/phpswoole>
+ __Discord__: <https://discord.swoole.dev>
+ __ä¸æææ¡£__: <https://wiki.swoole.com>
+ __ä¸æç¤¾åº__: <https://wiki.swoole.com/#/other/discussion>
## ð Awesome Swoole
Project [Awesome Swoole](https://github.com/swoole/awesome-swoole) maintains a curated list of awesome things related to Swoole, including
* Swoole-based frameworks and libraries.
* Packages to integrate Swoole with popular PHP frameworks, including Laravel, Symfony, Slim, and Yii.
* Books, videos, and other learning materials about Swoole.
* Debugging, profiling, and testing tools for developing Swoole-based applications.
* Coroutine-friendly packages and libraries.
* Other Swoole related projects and resources.
## ⨠Event-based
The network layer in Swoole is event-based and takes full advantage of the underlying epoll/kqueue implementation, making it really easy to serve millions of requests.
Swoole 4.x uses a brand new engine kernel and now it has a full-time developer team, so we are entering an unprecedented period in PHP history which offers a unique possibility for rapid evolution in performance.
## â¡ Coroutine
Swoole 4.x or later supports the built-in coroutine with high availability, and you can use fully synchronized code to implement asynchronous performance. PHP code without any additional keywords, the underlying automatic coroutine-scheduling.
Developers can understand coroutines as ultra-lightweight threads, and you can easily create thousands of coroutines in a single process.
### MySQL
Concurrency 10K requests to read data from MySQL takes only 0.2s!
```php
$s = microtime(true);
Co\run(function() {
for ($c = 100; $c--;) {
go(function () {
$mysql = new Swoole\Coroutine\MySQL;
$mysql->connect([
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'root',
'database' => 'test'
]);
$statement = $mysql->prepare('SELECT * FROM `user`');
for ($n = 100; $n--;) {
$result = $statement->execute();
assert(count($result) > 0);
}
});
}
});
echo 'use ' . (microtime(true) - $s) . ' s';
```
### Mixed server
You can create multiple services on the single event loop: TCP, HTTP, Websocket and HTTP2, and easily handle thousands of requests.
```php
function tcp_pack(string $data): string
{
return pack('N', strlen($data)) . $data;
}
function tcp_unpack(string $data): string
{
return substr($data, 4, unpack('N', substr($data, 0, 4))[1]);
}
$tcp_options = [
'open_length_check' => true,
'package_length_type' => 'N',
'package_length_offset' => 0,
'package_body_offset' => 4
];
```
```php
$server = new Swoole\WebSocket\Server('127.0.0.1', 9501, SWOOLE_BASE);
$server->set(['open_http2_protocol' => true]);
// http && http2
$server->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
$response->end('Hello ' . $request->rawcontent());
});
// websocket
$server->on('message', function (Swoole\WebSocket\Server $server, Swoole\WebSocket\Frame $frame) {
$server->push($frame->fd, 'Hello ' . $frame->data);
});
// tcp
$tcp_server = $server->listen('127.0.0.1', 9502, SWOOLE_TCP);
$tcp_server->set($tcp_options);
$tcp_server->on('receive', function (Swoole\Server $server, int $fd, int $reactor_id, string $data) {
$server->send($fd, tcp_pack('Hello ' . tcp_unpack($data)));
});
$server->start();
```
### Coroutine clients
Whether you DNS query or send requests or receive responses, all of
Swoole框架PHP 异步网络通信引擎swoole-v5.1.2.zip
需积分: 0 165 浏览量
更新于2024-05-06
收藏 2.95MB ZIP 举报
《Swoole框架PHP异步网络通信引擎:深入解析swoole-v5.1.2》
Swoole,作为一款高性能的PHP扩展,为PHP提供了异步、非阻塞的网络通信引擎,极大地提升了PHP在处理高并发、长连接等场景下的性能。在swoole-v5.1.2版本中,它进一步优化了性能,增强了稳定性,并引入了一些新的特性和改进。
一、Swoole核心概念与特性
1. 异步多线程:Swoole采用了事件驱动的异步非阻塞IO模型,通过epoll(Linux)或kqueue(FreeBSD)等高效的IO复用技术,使得程序在等待IO操作时可以处理其他任务,从而提高了系统的并发能力。
2. 服务器模型:Swoole支持TCP/UDP服务器,HTTP服务器,WebSocket服务器等多种网络协议,且支持主进程、工作进程、工作线程等多进程/线程模型,灵活应对不同业务需求。
3. PHP协程:从4.2版本开始,Swoole引入了协程(Coroutine)支持,使得开发者可以在PHP中编写出无锁、无回调的并发代码,降低了异步编程的复杂性。
4. 内存管理:Swoole使用自己的内存池进行内存管理,减少了PHP的内存分配和释放开销,提升了性能。
二、swoole-v5.1.2新特性与改进
1. 协程调度优化:在v5.1.2版本中,Swoole对协程调度进行了优化,减少了不必要的上下文切换,提升了整体运行效率。
2. TCP延迟接受:新增TCP延迟接受功能,允许在客户端连接建立后暂时不接收数据,直到有实际的数据读取请求,减少了无效的内存占用。
3. HTTP2优化:增强了HTTP2协议的支持,提升了处理HTTP2连接的性能。
4. 重试机制:增加了网络错误的自动重试机制,提高了网络不稳定情况下的连接可靠性。
5. 日志系统:日志系统进行了改进,提供了更丰富的日志级别和日志格式选项,便于开发者调试和监控。
三、Swoole与SQL Server的结合
在PHP环境中,Swoole可以与SQL Server数据库进行高效交互。通过Swoole的异步客户端,可以实现非阻塞的数据库查询,尤其是在处理大量并发请求时,能够显著提升系统响应速度。此外,Swoole的协程特性使得在并发环境下可以避免传统的锁和回调问题,简化了数据库操作的代码逻辑。
四、Swoole与PHP的集成应用
1. 实时服务:例如在线聊天、实时推送等,Swoole的长连接特性可以保持用户与服务器的持久连接,降低网络延迟。
2. API服务器:对于高并发的API接口,Swoole可以提供更快的响应速度和更高的吞吐量。
3. Websocket服务:Swoole的WebSocket服务器可以轻松处理大量用户的实时交互需求,如游戏服务器、在线教育等。
4. 调度任务:Swoole的定时器功能可以实现定时任务,如定时发送邮件、清理缓存等。
Swoole框架在PHP中扮演着重要的角色,它不仅弥补了PHP在处理异步任务上的不足,还带来了更高的性能和更低的资源消耗。swoole-v5.1.2的更新进一步强化了这些优势,使得开发者在构建高性能、高并发的PHP应用时有了更强大的工具。通过掌握Swoole,开发者可以构建出更具竞争力的服务端应用,满足现代互联网的快速变化和高需求。

douluo998
- 粉丝: 2335
最新资源
- 10kV氧化锌避雷器技术规范.doc
- 海氏评估系统因素表及说明.doc
- 知名房地产工程现场精细化管理讲义(附案例).pdf
- 白云国际会议中心花城厅(原一层多功能厅)维护保养、1号楼东座三楼客房改造项目招标文件(第一标段).docx
- 3d3s吊车梁设计流程.doc
- 微信小程序开发资源汇总 .zip
- 微信小程序-公众号热门文章信息流.zip
- 淘宝客项目,支持App,微信小程序,QQ小程序.zip
- 国家电网公司优秀QC成果1764页-1953页.docx
- 酒店类微信小程序模板.zip
- 软弱土地基处理—教学讲稿.ppt
- 安全文明施工监理细则.doc
- 对工程总承包相关问题的认识.doc
- 患者外跑应急演练脚本.doc
- 桥深基坑土钉墙支护施工方案.doc
- 11G101系平法新规则交底广联达实训课程.ppt