Skip to content
This repository has been archived by the owner on Sep 10, 2024. It is now read-only.

Commit

Permalink
Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
albertcht authored Apr 14, 2018
1 parent 01bf8ae commit 33f2c07
Showing 1 changed file with 149 additions and 10 deletions.
159 changes: 149 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Laravel-Swoole

![php-badge](https://img.shields.io/badge/php-%3E%3D%205.5.9-8892BF.svg)
![php-badge](https://img.shields.io/badge/php-%3E%3D%207.1-8892BF.svg)
[![packagist-badge](https://img.shields.io/packagist/v/swooletw/laravel-swoole.svg)](https://packagist.org/packages/swooletw/laravel-swoole)
[![Total Downloads](https://poser.pugx.org/swooletw/laravel-swoole/downloads)](https://packagist.org/packages/swooletw/laravel-swoole)
[![travis-badge](https://api.travis-ci.org/swooletw/laravel-swoole.svg?branch=master)](https://travis-ci.org/swooletw/laravel-swoole)
Expand All @@ -11,7 +11,7 @@ This package provides a high performance HTTP server to speed up your laravel/lu

| PHP | Laravel | Lumen | Swoole |
|:-------:|:-------:|:-----:|:-------:|
| >=5.5.9 | ~5.1 | ~5.1 | >=1.9.3 |
| >=7.1 | ~5.1 | ~5.1 | >=1.9.3 |

## Installation

Expand Down Expand Up @@ -43,12 +43,14 @@ $app->register(SwooleTW\Http\LumenServiceProvider::class);

## Configuration

If you want to change the default configurations, please run the following command to generate a configuration file `swoole_http.php` in directory `config/`:
If you want to change the default configurations, please run the following command to generate configuration files `swoole_http.php` and `swoole_websocket.php` in directory `config/`:

```
$ php artisan vendor:publish
```

### swoole_http.php

`server.host`: The swoole_http_server host.

`server.port`: The swoole_http_server port.
Expand All @@ -67,6 +69,14 @@ For example, if you want to set the 'max_request':
]
```

`websocket`: The switch to turn on websocket feature.

```php
[
'websocket' => 'false',
]
```

`providers`: The service providers you want to reset on every request. It will re-register and reboot those service providers before requesting every time.

```php
Expand All @@ -77,6 +87,61 @@ For example, if you want to set the 'max_request':
]
```

`tables`: You can customize your swoole tables here. See [here](https://wiki.swoole.com/wiki/page/p-table.html) for more detailed information.

```php
[
'tables' => [
'table_name' => [
'size' => 1024,
'columns' => [
['name' => 'column_name', 'type' => Table::TYPE_STRING, 'size' => 1024],
]
],
]
]
```

### swoole_websocket.php

`handler`: Websocket handler for onOpen and onClose callback function. Replace this handler before you start it.

```php
[
// handler must implement \SwooleTW\Http\Websocket\HandlerContract
handler' => SwooleTW\Http\Websocket\WebsocketHandler::class,
]
```

`handlers`: Websocket handlers mapping for onMessage callback. Message frames from clients will be parsed by formatter first (`SwooleTW\Http\Websocket\Formatters\DefaultFormatter`). It will dispatch the logic to matched event name.

> By default raw frame data will be expected as: `{"event":"event_name","data":"data_content"}`. If no events name matched, it will call your `onMessage` function of `WebsocketHandler`
```php
[
'handlers' => [
'event_name' => 'App\Handlers\ExampleHandler@function',
],
]
```

`default`: Default websocket driver. It only supports `table` at this momnet.

```php
[
'default' => 'table',
]
```

`formatter`: Default message formatter, replace it if you want to customize your websocket payload.

```php
[
// formatter must implement \SwooleTW\Http\Websocket\Formatters\FormatterContract
'formatter' => SwooleTW\Http\Websocket\Formatters\DefaultFormatter::class,
]
```

## Commands

> The swoole_http_server can only run in cli environment, and this package provides convenient artisan commands to manage it.
Expand All @@ -91,20 +156,53 @@ For example, if you want to set the 'max_request':
| `restart` | Restart Laravel Swoole |
| `reload` | Reload all worker process(Contain your business & Laravel/Lumen codes), exclude master/manger process |
| `infos` | Show PHP and Swoole basic miscs infos(including PHP version, Swoole version, Laravel version, server status and PID) |
| `publish` | Publish configuration file `swoole_http.php` to `config` folder of your project |
| `publish` | Publish configuration files `swoole_http.php` and `swoole_websocket.php` to `config` folder of your project |

Now, you can run the following command to start the **swoole_http_server**.

```
$ php artisan swoole:http start
```

## Get Swoole\Http\Server in your project
## Get related instances in your project

* Swoole\Http\Server: By `SwooleTW\Http\Server\Facades\Server` or `app('swoole.server')`

* SwooleTW\Http\Server\Table: By `SwooleTW\Http\Server\Facades\Table` or `app('swoole.table')`

```php
// app('swoole.server') is a singleton instance
$swoole = app('swoole.server');
var_dump($swoole->stats());
// you can get your customized swoole tables like this
Table::get('table_name');

// get all defined tables
Table::getAll();
```

* SwooleTW\Http\Websocket\Websocket: By `SwooleTW\Http\Websocket\Facades\Websocket` or `app('swoole.websocket')`

> The usage of websocket refers to `socket.io`, so they look a liitle bit similar.
```php
// sending to sender-client only
Websocket::emit('message', 'this is a test');

// sending to all clients except sender
Websocket::broadcast()->emit('message', 'this is a test');

// sending to all clients in 'game' room(channel) except sender
Websocket::broadcast()->to('game')->emit('message', 'nice game');

// sending to all clients in 'game' including sender client
Websocket::to('game')->emit('message', 'enjoy the game');

// sending to individual socketid 1
Websocket::broadcast()->to(1).emit('message', 'for your eyes only');

// join to subscribe the socket to a given channel (server-side):
Websocket::join('some room');

// leave to unsubscribe the socket to a given channel (server-side)
Websocket::leave('some room');
```

## Nginx Configuration
Expand Down Expand Up @@ -139,6 +237,8 @@ server {
proxy_set_header SERVER_PORT $server_port;
proxy_set_header REMOTE_ADDR $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
# IF https
# proxy_set_header HTTPS "on";
Expand Down Expand Up @@ -187,6 +287,13 @@ Transfer/sec: 1.55MB

> This is a rough description of the lifecycle in Swoole and Laravel. It may be helpful for you to know more about how this pakcage launches your Laravel application with swoole server.
* Initialize
* Create swoole tables.
* Prepare websocket.
* Create swoole server
* Configure swoole server
* Set swoole server listeners

* onStart()
* Create pid file.

Expand All @@ -195,24 +302,56 @@ Transfer/sec: 1.55MB
* Set framework type and base path.
* Load `/bootstrap/app.php`.
* Bootstrap framework.
* Bind swoole server, swoole table, room and websocket instances

* onRequest()
* Reset designated service providers
* Convert swoole request to illuminate request.
* Make `Illuminate\Contracts\Http\Kernel` (Laravel).
* Handle/dispatch HTTP request.
* Terminate request in Laravel, or reset middleware in Lumen.
* Convert illuminate response to swoole response.
* Send response to client.
* Unset request and response.

* onOpen()
* Convert swoole request to illuminate request.
* Dispatch request to related handler.

* onMessage()
* Set sender fd to websocket instance.
* Tansform payload data via formatter.
* Dispatch payload to related handler.

* onClose()
* Dispatch client's fd to related handler.
* Remove disconnected fd from all the rooms.

* onShutdown()
* Remove pid file.

## Notices

1. Please reload or restart the swoole_http_server after released your code. Because the Laravel program will be kept in memory after the swoole_http_server started. That's why the swoole_http_server has high performance.
2. Never use `dd()`, `exit()` or `die()` function to print your debug message. It will terminate your swoole worker unexpectedly.
3. You should have basic knowledge about multi-process programming and swoole. If you still write your code with traditional php concept, your app might have unexpected bugs.
3. `global` and `static` variables needs to be destroyed(reset) manually.
4. Infinitely appending element into static/global variable will lead to memory leak.
```
// Some class
class Test
{
public static $array = [];
public static $string = '';
}
// Controller
public function test(Request $req)
{
// Memory leak
Test::$array[] = $req->input('param1');
Test::$string .= $req->input('param2');
}
```
5. You should have basic knowledge about multi-process programming and swoole. If you still write your code with traditional php concept, your app might have unexpected bugs.

## Support

Expand Down

0 comments on commit 33f2c07

Please sign in to comment.