# 在php-fpm或apache中使用swoole
swoole扩展中swoole_server只能在cli模式下使用,在其他模式下会抛出致命错误。而swoole_client和swoole_event是可以用在php-fpm或apache+mod_php5中的。
需要注意的是使用swoole_client异步和swoole_event,在所有数据收到并处理完后,一定要执行$client->close()、swoole_event_del或swoole_event_exit,否则swoole无法得知什么时候要停止epoll wait。
### 同步swoole_client
~~~
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC); //同步阻塞
$client->connect('127.0.0.1', 9501) or die("connect failed\n");
$client->send(str_repeat("A", 600));
$data = $client->recv(700, 0) or die("recv failed\n);;
echo "recv: ",$data,"\n";
~~~
### 异步swoole_client
~~~
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非阻塞
$client->on("connect", function(swoole_client $cli) {
$cli->send("GET / HTTP/1.1\r\n\r\n");
});
$client->on("receive", function(swoole_client $cli, $data){
echo "Received: $data";
$cli->close();
});
$client->on("error", function(swoole_client $cli){
exit("error\n");
});
$client->on("close", function(swoole_client $cli){
echo "Connection close";
});
$client->connect('127.0.0.1', 9501, 0.5);
echo "connect to 127.0.0.1:9501";
//for PHP5.3-
//swoole_event_wait();
~~~
| Swoole流程 |
|-----|
![](https://box.kancloud.cn/2015-07-20_55aca2bd2546a.)