1.简介:
- swoole是php的一类扩展;
- swoole用以处理异步及多线程业务场景;
- swoole支持TCP、UDP、UnixSocket 3种协议,支持IPv4和IPv6,支持SSL/TLS单向双向证书的隧道加密;
- 官网: 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)