把task加入websocket服务端程序

  • 服务端代码
<?php
//task任务要实现两个方法onfinish ontask
//还要设置worker_num
date_default_timezone_set("PRC"); //设置为本地时间

class taskserver
{
    CONST host ="0.0.0.0";
    CONST port =9502;
    public $sw = null;
    public function __construct()
    {
        $this->sw = new swoole_websocket_server(taskserver::host,taskserver::port);
        $this->sw->set([
            'worker_num'=>4,
            'task_worker_num'=>4
        ]);

        $this->sw->on('open',[$this,'onopen']);
        $this->sw->on('message',[$this,'onmessage']);
        $this->sw->on('task',[$this,'ontask']);
        $this->sw->on('finish',[$this,'onfinish']);
        $this->sw->on('close',[$this,'onclose']);
        $this->sw->start();
    }

    public function onopen($serv,$request)
    {
        echo "来自{$request->fd}的连接已经建立\n";
        echo "cpu数量:".SWOOLE_CPU_NUM()."\n";
    }

    public function onmessage($serv,$frament)
    {
        echo "finish标识符---{$frament->finish}--opcode:{$frament->opcode}---fd:标识符{$frament->fd}\n";
        //加入这里有个耗费时间的操作
        //这个数组没什么实际意义,只不过是模拟一个任务
        $mytask=array([
            "name"=>'陈培昌',
            'age'=>22
        ]);
        $serv->task($mytask);//把任务头送进进程池,$mytask必须是可序列化的数据类型
        $serv->push($frament->fd,"回馈来自客户端{$frament->fd}的数据{$frament->data}---时间是".date("Y-m-d H:i:s")."\n");
    }

    public function ontask($serv,$task_id,$worker_id,$mytask)
    {
        //这里是真正执行阻塞任务的地方
        //纯属无聊,打印看看是这个任务---也就是$mytask到底什么货色
        print_r($mytask);
        //这段模拟阻塞/耗时操作
        sleep(10);
        //返回处理结果
        return "想去找小烤肠练巴西柔术";

    }

    public function onfinish($serv,$task_id,$data)
    {
        echo "{$task_id}就绪,并返回结果----{$data}";
    }
    public function onclose($serv,$fd)
    {
        echo "句柄:{$fd}关闭连接\n";
    }
}
$cpc = new taskserver();
  • 运行结果

打印:

来自1的连接已经建立
cpu数量:4
finish标识符---1--opcode:1---fd:标识符1
Array
(
[0] => Array
(
[name] => 陈培昌
[age] => 22
)

)

--------------------------------10秒后又打印

0就绪,并返回结果----想去找小烤肠练巴西柔术

猜你喜欢

转载自www.cnblogs.com/saintdingspage/p/10982691.html