tcp 心跳,定时器

心跳解决问题:客户端到服务端 有设备休眠,比如路由器,交换机等导致连接断开

<?php
/**
 * Created by PhpStorm.
 * User: zhangheg
 * Date: 2019/3/23
 * Time: 14:52
 */

$client = new Swoole\Client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function(swoole_client $cli) {
    $cli->send("GET / HTTP/1.1\r\n\r\n");
});
//必须注册所有时间
$client->on("receive", function(swoole_client $cli, $data){
    echo "Receive: $data";//接收消息
    //$cli->send(str_repeat('A', 100)."\n");
    sleep(1);
});
$client->on("error", function(swoole_client $cli){
    echo "error\n";
});
$client->on("close", function(swoole_client $cli){
    echo "超过15秒没发送断开了 Connection close\n";
});
$client->connect('127.0.0.1', 9501) || exit('连接失败');

//定时器保持长链接
swoole_timer_tick(9000,function () use ($client){
   $client->send(1);
});
echo "写日志".PHP_EOL;
echo "请求api".PHP_EOL;

<?php
/**
 * Created by PhpStorm.
 * User: zhangheg
 * Date: 2019/3/23
 * Time: 14:52
 */

$client = new Swoole\Client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function(swoole_client $cli) {
    $cli->send("GET / HTTP/1.1\r\n\r\n");
});
//必须注册所有时间
$client->on("receive", function(swoole_client $cli, $data){
    echo "Receive: $data";//接收消息
    //$cli->send(str_repeat('A', 100)."\n");
    sleep(1);
});
$client->on("error", function(swoole_client $cli){
    echo "error\n";
});
$client->on("close", function(swoole_client $cli){
    echo "超过15秒没发送断开了 Connection close\n";
});
$client->connect('127.0.0.1', 9501) || exit('连接失败');

//定时器保持长链接
swoole_timer_tick(9000,function () use ($client){
   $client->send(1);
});
echo "写日志".PHP_EOL;
echo "请求api".PHP_EOL;

发表评论

电子邮件地址不会被公开。 必填项已用*标注