Swoole的push和listen用法

1.1Push在控制器中的用法

swoole_server::$connections

TCP连接迭代器,可以使用foreach遍历服务器当前所有的连接,此属性的功能与swoole_server->connnection_list是一致的,但是更加友好。遍历的元素为单个连接的fd。

注意$connections属性是一个迭代器对象,不是PHP数组,所以不能用var_dump或者数组下标来访问,只能通过foreach进行遍历操作。

foreach($server->connections as $fd)
{
    $server->send($fd, "hello");
}

echo "当前服务器共有 ".count($server->connections). " 个连接\n";

此属性在1.7.16以上版本可用
连接迭代器依赖pcre库(不是PHP的pcre扩展),未安装pcre库无法使用此功能
pcre库的安装方法, http://wiki.swoole.com/wiki/page/312.html

代码展示:

<?php
namespace app\index\controller;

class Index
{
    public function push()
    {   
        foreach($_POST['web_socket']->connections as $fd)
        {
            $_POST['web_socket']->push($fd, "hello,你去死吧!");
        }
        echo "当前服务器共有 ".count($_POST['web_socket']->connections). " 个连接\n";
    }
}

1.2 聊天(connections)

$this->ws = new swoole_websocket_server(self::HOST, self::PORT);
$this->ws->listen(self::HOST, self::CHART_PORT, SWOOLE_SOCK_TCP);
//推荐使用connections这种方式,redis方式也可以
foreach($_POST['http_server']->ports[1]->connections as $fd) {
    $_POST['http_server']->push($fd, json_encode($data));
}


2.2 平滑重启

/**
 * 设置进程名,为后续平滑重启进程
 * @param $server
 */
public function onStart($server) {
    swoole_set_process_name("live_master");
}        

    reload.sh

echo "loading..."
pid=`pidof live_master`
echo $pid
kill -USR1 $pid
echo "loading success"
# linux 信号控制:USR1 平滑重载所有worker进程并重新载入配置和二进制模块

运行的时候加&,后台执行,可怜我的linux,太渣渣·····

















猜你喜欢

转载自blog.csdn.net/feiwutudou/article/details/80202590