我的环境是Ubontu14.04
1、apt-get install libpcre3-dev
2、sudo pecl install swoole
成功后,会提示如下
install ok: channel://pecl.php.net/swoole-1.7.8
configuration option “php_ini” is not set to php.ini location
You should add “extension=swoole.so” to php.ini
zzs@ubuntu:~$ sudo vim /etc/php5/mods-available/swoole.ini
3、sudo vim /etc/php5/mods-available/swoole.ini
添加如下
; configuration for php Swoole module
extension=swoole.so
4、运行 php -m | grep swoole
若是没有显示 swoole ,进行以下操作
5、sudo ln -s /etc/php5/mods-available/swoole.ini /etc/php5/cli/conf.d/20-swoole.ini
6、再运行 php -m | grep swoole
若还是没有显示,再进行以下操作
sudo ln -s /etc/php5/mods-available/swoole.ini /etc/php5/apache2/conf.d/20-swoole.ini
sudo ln -s /etc/php5/mods-available/swoole.ini /etc/php5/fpm/conf.d/20-swoole.ini
7、再运行 php -m | gerp swoole
查看 php -m | grep swoole
会显示 swoole
再使用php代码进行测试,
client.php
<?php
class Client{
private $client;
public function __construct(){
$this->client = new swoole_client(SWOOLE_SOCK_TCP);
}
public function connect(){
if (!$this->client->connect("127.0.0.1", 9501, 1)) {
echo "Error: {$fp->errMsg}[{$fp->errCode}]\n";
}
$message = $this->client->recv();
echo "Get Message From Server:{$message}\n";
fwrite(STDOUT, "请输入消息:");
$msg = trim(fgets(STDIN));
$this->client->send($msg);
}
}
$client = new Client();
$client->connect();
server.php
<?php
class Server{
private $serv;
public function __construct(){
$this->serv = new swoole_server("0.0.0.0", 9501);
$this->serv->set(array(
'worker_num' => 8,
'daemonize' => false,
'max_request' => 10000,
'dispatch_mode' => 2,
'debug_mode' => 1
));
$this->serv->on('Start', array($this, 'onStart'));
$this->serv->on('Connect', array($this, 'onConnect'));
$this->serv->on('Receive', array($this, 'onReceive'));
$this->serv->on('Close', array($this, 'onClose'));
$this->serv->start();
}
public function onStart($serv){
echo "Start\n";
}
public function onConnect($serv, $fd, $from_id){
$serv->send($fd, "Hello {$fd}!");
}
public function onReceive(swoole_server $serv, $fd, $from_id, $data){
echo "Get Message From Client {$fd}:{$data}\n";
}
public function onClose($serv, $fd, $from_id){
echo "Client {$fd} close connection\n";
}
}
// 启动服务器
$server = new Server();
开启两个端口进行测试,如下所示