Swoole是php的一个扩展。它的核心目标是解决php在实现一些高访问服务器服务时可能遇到的一系列问题。这些问题往往是原生php解决不了的。非常方便和高效的解决方案。对于这个问题,公司一般会使用其他技术,比如使用java或者其他语言。但是有了Swoole,由于底层全部用C语言实现,其优异的性能备受追捧。由于以往php应用场景的局限性,据说Swoole重新定义了php。Swoole简介:Swoole是一个php高性能异步网络通信引擎,支持TCP、UDP、UnixSocket、HTTP、WebSocket服务。Swoole可广泛应用于互联网、移动通信、企业软件、云计算、网络游戏、物联网(IOT)、车联网、智能家居等领域。安装:这里我使用的是ubuntu16.04系统。首先,我需要安装Swoole依赖的编译环境。命令如下:sudoapt-getinstall\build-essential\gcc\g++\autoconf\libiconv-hook-dev\libmcrypt-dev\libxml2-dev\libmysqlclient-dev\libcurl4-openssl-dev\libjpeg8-dev\libpng12-dev\libfreetype6-dev\安装完这些就是php的安装,这里选择php7.2版本。注意,如果我们使用Swoole,则不需要安装php-fpm。sudoapt-getinstallsoftware-properties-commonpython-software-propertiessudoadd-apt-repositoryppa:ondrej/php&&sudoapt-getupdatesudoapt-get-yinstallphp7.2sudo-yapt-getinstallphp7.2-mysqlphp7.2-curlphp7.2-jsonphp7.2-mbstringphp7.2-xmlphp7.2-intlphp7.2-dev以下扩展可以按需要安装:sudoapt-getinstallphp7.2-gdsudoapt-get安装php7.2-soapsudoapt-get安装php7.2-gmpsudoapt-get安装php7.2-odbcsudoapt-get安装php7.2-pspellsudoapt-get安装php7.2-bcmathsudoapt-getinstallphp7.2-enchantsudoapt-getinstallphp7.2-imapsudoapt-getinstallphp7.2-ldapsudoapt-getinstallphp7.2-opcachesudoapt-getinstallphp7.2-readlinesudoapt-getinstallphp7.2-sqlite3sudoapt-getinstallphp7.2-xmlrpcsudoapt-getinstallphp7.2-bz2sudoapt-getinstallphp7.2-interbasesudoapt-getinstallphp7.2-pgsqlsudoapt-getinstallphp7.2-重新编码sudoapt-getinstallphp7.2-sybasesudoapt-getinstallphp7.2-xslsudoapt-getinstallphp7.2-cgisudoapt-getinstallphp7.2-dbasudoapt-getinstallphp7.2-phpdbgsudoapt-getinstallphp7.2-snmpsudoapt-getinstallphp7.2-tidysudoapt-getinstallphp7.2-zip安装好php后,需要到以下地址下载源码包,才能继续安装Swoole扩展。https://github.com/swoole/swo...下载后解压编译安装。cdswoole-src-4.2.0/phpize./configuresudomakesudomakeinstall安装完成后进入/etc/php目录,打开php.ini文件,写入如下内容:extension=swoole.so运行完成后,输入php-m,查看swoole扩展是否安装成功。至此,Swoole的环境搭建完成。那么接下来当然是写一个小例子来体验一下。创建一个server.php文件,代码如下:ip=$ip;$this->port=$port;}publicfunctionrun(){//创建swoole_server实例$this->createSwooleServer();$this->server->set(array('worker_num'=>5,'daemonize'=>false,));$this->server->on('Start',array($this,'onStart'));$this->server->on('Connect',array($this,'onConnect'));$this->server->on('Receive',array($this,'onReceive'));$this->server->on('Close',array($this,'onClose'));$this->server->start();}privatefunctioncreateSwooleServer(){$this->server=newswoole_server($this->ip,$this->port);}//服务启动时触发publicfunctiononStart($serv){echo"ServerStart\n";}//客户端连接时触发publicfunctiononConnect($serv,$fd,$from_id){echo"Client{$fd}connection\n";}//监听数据接收事件publicfunctiononReceive(swoole_server$serv,$fd,$from_id,$data){echo"GetMessageFromClient{$fd}:{$data}\n";}//触发publicfunctiononClose($serv,$fd,$whenclientclosestheconnectionfrom_id){echo"Client{$fd}closeconnection\n";}}$server=newserver("0.0.0.0",8899);$服务器->运行();运行phpserver.php,可以看到ServerStartsuccessfully输出说明服务器已经成功启动,接下来就是使用客户端连接了。这里我就不写客户端的代码了,直接使用curl请求8899端口的服务。如图:解释:根据我们的服务端程序,监听客户端的连接事件,输出Client1连接,然后监听消息接收事件。由于Curl默认发送HTTP请求,您将看到收到的整个HTTP请求消息被打印出来。最后我们在客户端按ctrlc断开连接,终于看到客户端关闭的信息。
