作为程序员一定要保持良好的睡眠,才能好编程

swoole在线用户处理相关方案集锦

发布时间:2019-04-02

前一章节说明了swoole聊天室的内容,


Swoole聊天室功能实现


那么 swoole 的websocket 连接用户,是如何保存的呢?


如何维护这么所有的连接的一个集合呢?


列举三种方案:


1、swoole提供了一个 connections

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


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

foreach($server->connections as $fd)
{    $server->send($fd, "hello");
}echo "当前服务器共有 ".count($server->connections). " 个连接\n";


注意事项:

连接迭代器依赖pcre库(不是PHP的pcre扩展),未安装pcre库无法使用此功能

pcre库的安装方法, http://wiki.swoole.com/wiki/page/312.html

4.1.0以上版本移除了pcre依赖



2、redis版本


1、当onopen的时候,保存fd到redis有序集合


2、当onMessage的时候 获取到有序集合所有用户fd 遍历发送信息


3、当onClose的时候 把fd 这个用户从 有序集合中移除


注意:每次重新启动,需要清空集合中的连接。


<?php
 
 
 class Ws{
    public $server=null;
        public $setAttrs=[];
        
        CONST HOST="0.0.0.0";
        CONST PORT=9992;
    public function __construct(){
    
            //如果我们的服务进行重新启动,查看redis是否存在以前存在的fd ,直接清空
    
    
        $this->server=new swoole_websocket_server(self::HOST,self::PORT);
        $this->server->on("open",[$this,"onOpen"]);
        
        $this->server->on("message",[$this,"onMessage"]);
        $this->server->on("close",[$this,"onClose"]);
    }
         
         
    public function onOpen($server,$frame){
                //将fd 放入redis 有序集合
                echo $frame->fd."---连接成功\n";
    }
         
    public function onMessage($server,$frame){
   		//从redis有序集合读取fd 循环遍历发送数据    
		//$server->push($frame->fd,"服务器返回消息说:".$frame->data."--".date("Y-m-d H:i:s"));
    }
 
    public function onClose($server,$fd){
                           
        echo $fd." 客户端已经关闭";
     }
         
 
 
    /**
     * @param $key worker_num
     * @param $val 2
     */
    public function set($key,$val){
        $this->setAttrs[$key]=$val;
    }
 
    //启动服务
    public function start(){
    $this->server->set($this->setAttrs);
    $this->server->start();
    } 
}

$_ws=new Ws(); 
//echo $_ws->getMemoryUsage();
$_ws->set("worker_num",1);
$_ws->set("daemonize",0);
$_ws->start();





3、memory table方式


稍后完善