PHP swoole (1.安装与demo)

1.简介:

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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,568评论 2 45
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 在这个微信,QQ遍布全球的世界里,越来越多的人们迫切自己的时间得到充实,希望自己的话题能有人回复,越来越多的人患有...
    wanna_dance阅读 1,036评论 6 23
  • ​作者:蓓蓓梦想家 真正的触动应该是从老师推荐的日剧《我的家里空无一物》开始的。和女主角一样,我是个完全不懂得如何...
    袁春楠阅读 257评论 0 1
  • 我也不知道是怎么想的,但心里总有一个声音告诉我,不要丢了你,我一直是个理智的人,可是,却不知道怎么了,总会胡思乱想...
    给你的小书情阅读 214评论 0 0