1.簡介:
- swoole是php的一類擴展;
- swoole用以處理異步及多線程業(yè)務場景;
- swoole支持TCP垄惧、UDP搓谆、UnixSocket 3種協(xié)議炒辉,支持IPv4和IPv6,支持SSL/TLS單向雙向證書的隧道加密;
- 官網(wǎng): http://www.swoole.com/
- 中文: https://wiki.swoole.com/
- API文檔: https://rawgit.com/tchiotludo/swoole-ide-helper/english/docs/index.html
- github: https://github.com/swoole/swoole-src/
2.安裝(ver Linux):
需要支持:
Version-1: PHP 5.3.10 or later
Version-2: PHP 5.5.0 or later
Linux, OS X and basic Windows support
GCC 4.4 or later安裝方式1:使用pecl安裝
pecl install swoole
- 安裝方式2:源碼安裝
sudo apt-get install php5-dev
git clone https://github.com/swoole/swoole-src.git
cd swoole-src
phpize
./configure
make && make install
- 更改PHP配置,引用swoole.so擴展:
sudo vi /etc/php/cli/php.ini
extension=swoole.so
- 重啟php及nginx service;
- 查看PHP是否引用擴展:
php -m
或
php -r "echo(phpinfo());"
3.示例:
- Server:
// create a server instance
$serv = new swoole_server("127.0.0.1", 9501);
// attach handler for connect event, once client connected to server the registered handler will be executed
$serv->on('connect', function ($serv, $fd){
echo "Client:Connect.\n";
});
// attach handler for receive event, every piece of data received by server, the registered handler will be
// executed. And all custom protocol implementation should be located there.
$serv->on('receive', function ($serv, $fd, $from_id, $data) {
$serv->send($fd, $data);
});
$serv->on('close', function ($serv, $fd) {
echo "Client: Close.\n";
});
// start our server, listen on port and be ready to accept connections
$serv->start();
- Client:
$client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, 0.5))
{
die("connect failed.");
}
if (!$client->send("hello world"))
{
die("send failed.");
}
$data = $client->recv();
if (!$data)
{
die("recv failed.");
}
$client->close();
- 關閉進程(shell)
via https://segmentfault.com/a/1190000006052748
#! /bin/bash
ps -eaf |grep "server.php" | grep -v "grep"| awk '{print $2}'|xargs kill -9
- 正確輸出:
php swoole_server.php
Client: Connect.
Client: Close.
Server: hello world
(to be continued)