安装准备

安装swoole前必须保证系统已经安装了下列软件

参考

https://github.com/LinkedDestiny

php-5.3.10    // 或更高版本
gcc-4.4       //或更高版本
make
autoconf

安装swoole的PHP扩展

wget https://github.com/swoole/swoole-src/archive/swoole-1.8.2-stable.tar.gz
tar -zxvf swoole-1.8.2-stable
cd swoole-src-swoole-1.8.2-stable/
/usr/local/php/bin/phpize
./configure
make && make install

配置php.ini

编译安装成功后,修改php.ini加入

extension=swoole.so

测试

服务器端(server.php)

<?php
/**
 * 服务端
 */
$serv = new swoole_server("0.0.0.0", 9501);
$serv->on('connect', function ($serv, $fd){
    echo "Client:Connect.\n";
});
$serv->on('receive', function ($serv, $fd, $from_id, $data) {
    $serv->send($fd, 'Swoole: '.$data);
});
$serv->on('close', function ($serv, $fd) {
    echo "Client: Close.\n";
});
$serv->start();

客户端 (client.php)

<?php
    $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
    $client->on("connect", function($cli) {
        $cli->send("hello world\n");
    });
    $client->on("receive", function($cli, $data){
        echo "Receive: $data\n";
    });
    $client->on("error", function($cli){
        echo "connect fail\n";
    });
    $client->on("close", function($cli){
        echo "close\n";
    });
    $client->connect('127.0.0.1', 9501, 0.5);

测试

先运行服务端(无任何输出)

clipboard.png

运行客户端后 在查看服务端,会发现有输出了,表示成功~!

clipboard.png


YPHP
967 声望77 粉丝

免费好用的素材站:[链接]