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进程并重新载入配置和二进制模块