入门指引 Server Client Process AsyncIO Memory HttpServer WebSocket 高级 其他

发布于 2015-08-09 09:42:39 | 706 次阅读 | 评论: 0 | 来源: 网络整理

swoole扩展中swoole_server只能在cli模式下使用,在其他模式下会抛出致命错误。 而swoole_client和swoole_event是可以用在php-fpm或apache+mod_php5中的。

需要注意的是使用swoole_client异步和swoole_event,在所有数据收到并处理完后,一定要执行$client->close()、swoole_event_del或swoole_event_exit,否则swoole无法得知什么时候要停止epoll wait。

同步swoole_client

$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC); //同步阻塞
$client->connect('127.0.0.1', 9501) or die("connect failedn");

$client->send(str_repeat("A", 600));
$data = $client->recv(700, 0) or die("recv failedn);;
echo "recv: ",$data,"n";

异步swoole_client

<?php
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非阻塞

$client->on("connect", function(swoole_client $cli) {
    $cli->send("GET / HTTP/1.1rnrn");
});

$client->on("receive", function(swoole_client $cli, $data){
    echo "Received: $data";
    $cli->close();
});

$client->on("error", function(swoole_client $cli){
    exit("errorn");
});

$client->on("close", function(swoole_client $cli){
    echo "Connection close";
});

$client->connect('127.0.0.1', 9501, 0.5);

echo "connect to 127.0.0.1:9501";
//for PHP5.3-
//swoole_event_wait();
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务