写在前面的废话

《swoole源码分析》已经写了13章,整个swoole的核心架构基本都分析的差不多了。于是心里一直以来想整理swoole的文档并写一份教程的想法就再度浮了出来。实话说,我接触swoole乃至接触PHP都仅有9个月的时间,而自7月份以来一直在公司做Android开发,也就没有了使用swoole的机会。所以,现在我只能写出一份入门级教程,帮助刚刚接触swoole的人理解和使用swoole写一些简单的例子,从而初步掌握swoole的用法。


Git地址:https://github.com/LinkedDestiny/swoole-doc

第一章 环境搭建及扩展安装

环境说明: 系统:Ubuntu14.04 (安装教程包括CentOS6.5) PHP版本:PHP-5.5.10 swoole版本:1.7.6-stable

PHP安装

要用swoole,首先需要有PHP环境。由于swoole的某些特性,最好是能够从源码编译安装PHP,这样在使用过程中可以避免很多不必要的错误。 PHP下载地址:http://php.net/ 在这里挑选你想用的版本即可。下载源码包后,解压至本地任意目录(保证读写权限),留待使用。 安装PHP前,需要安装编译环境和PHP的相关依赖。下面是相关命令: Ubuntu环境下:

  1. sudo apt-get install build-essential gcc g++ autoconf libiconv-hook-dev libmcrypt-dev libxml2-dev libmysqlclient-dev libcurl4-openssl-dev libjpeg8-dev libpng12-dev libfreetype6-dev

CentOS环境下:

  1. yum -y install gcc gcc-c++ autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers gd gd2 gd-devel gd2-devel perl-CPAN pcre-devel

(注:以上命令是我在实际使用中验证过的可以使用的,可能会和其他教程提供的命令不同) 当上述命令执行后,即可开始安装PHP。命令如下:

  1. cd php-5.5.10/
  2. ./configure --prefix=/usr/local/php --with-config-file-path=/etc/php --enable-fpm --enable-pcntl --enable-mysqlnd --enable-opcache --enable-sockets --enable-sysvmsg --enable-sysvsem --enable-sysvshm --enable-shmop --enable-zip --enable-ftp --enable-soap --enable-xml --enable-mbstring --disable-rpath --disable-debug --disable-fileinfo --with-mysql=mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-pcre-regex --with-iconv --with-zlib --with-mcrypt --with-gd --with-openssl --with-mhash --with-xmlrpc --with-curl --with-imap-ssl
  3. sudo make
  4. sudo make install
  5. sudo cp php.ini-development /etc/php/

至此,PHP已经成功安装,但是此时在终端里是无法直接通过php —version查看php版本的还需要将PHP的可执行目录添加到环境变量中。 使用Vim/Sublime打开~/.bashrc,在末尾添加如下内容:

  1. export PATH=/usr/local/php/bin:$PATH
  2. export PATH=/usr/local/php/sbin:$PATH

保存后,终端输入命令:

  1. source ~/.bashrc

此时即可通过php —version查看php版本,看到如下内容:

  1. PHP 5.5.10 (cli) (built: Apr 26 2014 09:46:14)
  2. Copyright (c) 1997-2014 The PHP Group
  3. Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies

即说明安装成功。

Swoole安装

安装完PHP后,即可安装swoole扩展。 swoole扩展下载地址:https://github.com/swoole/swoole-src/releases 尽量选择stable版本,alpha版本最好仅用于实验新特性。 解压源码至任意目录,执行如下命令:

  1. cd swoole-src-swoole-1.7.6-stable/
  2. phpize
  3. ./configure --enable-async-mysql
  4. sudo make
  5. sudo make install

(注:swoole的./configure有很多额外参数,可以通过./configure —help命令查看,这里仅开启其中async-mysql项,其他均选择默认项) 安装完成后,进入/etc/php目录下,打开php.ini文件,在其中加上如下一句:

  1. extension=swoole.so

随后在终端中输入命令

  1. php -m

查看扩展安装情况。如果在列出的扩展中看到了swoole,则说明安装成功。

基本实例

下面贴一个基本的基于swoole的echo服务器

  1. // Server
  2. class Server
  3. {
  4. private $serv;
  5. public function __construct() {
  6. $this->serv = new swoole_server("0.0.0.0", 9501);
  7. $this->serv->set(array(
  8. 'worker_num' => 8,
  9. 'daemonize' => false,
  10. 'max_request' => 10000,
  11. 'dispatch_mode' => 2,
  12. 'debug_mode'=> 1
  13. ));
  14. $this->serv->on('Start', array($this, 'onStart'));
  15. $this->serv->on('Connect', array($this, 'onConnect'));
  16. $this->serv->on('Receive', array($this, 'onReceive'));
  17. $this->serv->on('Close', array($this, 'onClose'));
  18. $this->serv->start();
  19. }
  20. public function onStart( $serv ) {
  21. echo "Start\n";
  22. }
  23. public function onConnect( $serv, $fd, $from_id ) {
  24. $serv->send( $fd, "Hello {$fd}!" );
  25. }
  26. public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
  27. echo "Get Message From Client {$fd}:{$data}\n";
  28. }
  29. public function onClose( $serv, $fd, $from_id ) {
  30. echo "Client {$fd} close connection\n";
  31. }
  32. }
  33. // 启动服务器
  34. $server = new Server();

从代码中可以看出,创建一个swoole_server基本分三步:

  1. 通过构造函数创建swoole_server对象
  2. 调用set函数设置swoole_server的相关配置选项
  3. 调用on函数设置相关回调函数 关于set配置选项以及on回调函数的具体说明,请参考我整理的swoole文档( 配置选项)

这里只给出简单介绍。onStart回调在server运行前被调用,onConnect在有新客户端连接过来时被调用,onReceive函数在有数据发送到server时被调用,onClose在有客户端断开连接时被调用。 这里就可以大概看出如何使用swoole:在onConnect处监听新的连接;在onReceive处接收数据并处理,然后可以调用send函数将处理结果发送出去;在onClose处处理客户端下线的事件。

下面贴出客户端的代码:

  1. <?php
  2. class Client
  3. {
  4. private $client;
  5. public function __construct() {
  6. $this->client = new swoole_client(SWOOLE_SOCK_TCP);
  7. }
  8. public function connect() {
  9. if( !$this->client->connect("127.0.0.1", 9501 , 1) ) {
  10. echo "Error: {$fp->errMsg}[{$fp->errCode}]\n";
  11. }
  12. $message = $this->client->recv();
  13. echo "Get Message From Server:{$message}\n";
  14. fwrite(STDOUT, "请输入消息:");
  15. $msg = trim(fgets(STDIN));
  16. $this->client->send( $msg );
  17. }
  18. }
  19. $client = new Client();
  20. $client->connect();

这里,通过swoole_client创建一个基于TCP的客户端实例,并调用connect函数向指定的IP及端口发起连接请求。随后即可通过recv()和send()两个函数来接收和发送请求。需要注意的是,这里我使用了默认的同步阻塞客户端,因此recv和send操作都会产生网络阻塞。

(以上两段代码均以上传git,地址:https://github.com/LinkedDestiny/swoole-doc/tree/master/src/01)

下章预告:swoole的task使用以及实例:简单聊天室