websocket的推送在控制器中调用和实现

本文介绍了一个基于Swoole的WebSocket服务器实现案例,通过面向对象的方式组织代码,实现了消息推送、任务处理等功能,并展示了如何从客户端连接并发送消息。

首先,websocket是基于Server的子类,所以可以调用Server的一部分方法,但是需要监听其他的端口,并在控制器中加载调用swoole_client方法

话不多说,上代码;

封装的web_socket.php

<?php

namespace app\common;
include 'Predis.php';
/**
*    socket面向对象的编译
*/
class Ws
{
    CONST HOST='0.0.0.0';
    CONST PORT='9501';
    public $ws=null;
    public $getmsg=null;
    public $server=null;

    public function __construct()
    {   
        $this->ws=new \swoole_websocket_server(self::HOST,self::PORT);
        $this->ws->set([
            //启动task必须要设置其数量
            'worker_num' => 4,
            'task_worker_num' => 4,
        ]);
        //监听新端口
        $this->server=$this->ws->listen("127.0.0.1", 9502, SWOOLE_SOCK_TCP);
        //关闭websocket模式
        $this->server->set([
            'open_websocket_protocol' => false,
        ]);

        $this->ws->on("start", [$this, 'onStart']);
        $this->ws->on('open',[$this,'onopen']);
        $this->server->on("receive", [$this, 'onReceive']);
        $this->server->on("close", [$this, 'onclose']);
        $this->ws->on('message',[$this,'onmessage']);
        $this->ws->on('task',[$this,'onTask']);
        $this->ws->on('finish',[$this,'onFinish']);
        $this->ws->on('close',[$this,'onclose']);
        $this->ws->start();
    }
    //监听数据接收事件
    public function onReceive($serv, $fd, $from_id, $data)
    {
        $this->ws->push(Predis::getInstance()->get('fd'), $data);
    }
    /**
     * 设置进程名,为后续平滑重启进程
     * @param $server
     */
    public function onStart($server) {
        swoole_set_process_name("live_master");
    }      
   /**
        监听开启事件的回调
    */
    public function onopen($server, $request)
    {
        Predis::getInstance()->set('fd',$request->fd);
        $server->push($request->fd,'小子,面向对象你也连接成功了');
    }
    
    /**
        监听接收事件的回调
    */
    public function onmessage($server, $frame)
    {
        $server->push($frame->fd, "{$frame->data}");
    }
    /**
        监听关闭事件的回调
    */
    public function onclose($ser, $fd)
    {
        print_r("你好,我的{$fd}\n");
    }

    /**
    *   $serv           服务
    *   $task_id        任务ID,由swoole扩展内自动生成,用于区分不同的任务
    *   $src_worker_id  $task_id和$src_worker_id组合起来才是全局唯一的,不同的worker进程投递的任务ID可能会有相同
    *   $data           是任务的内容
    */
     public function onTask($serv,$task_id,$src_worker_id,$data)
    {
        //在终端输出
        print_r($data).'/n';
        //执行耗时任务
        sleep(10);
        //回调于onFinish
        return '你成了-A';
    }
    /**
    *   $task_id        是任务的ID
    *   $data           是任务处理的结果内容
    */
     public function onFinish($serv,$task_id,$data)
    {
        print_r($data).'/n';
    }

}

new Ws();


 

include 'Predis.php';

<?php
/**
 * Created by PhpStorm.
 * User: baidu
 * Date: 18/3/26
 * Time: 上午3:52
 */
namespace app\common;

class Predis {
    public $redis = "";
    /**
     * 定义单例模式的变量
     * @var null
     */
    private static $_instance = null;

    public static function getInstance() {
        if(empty(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    private function __construct() {
        $this->redis = new \Redis();
        $result = $this->redis->connect('127.0.0.1',6379);
        if($result === false) {
            throw new \Exception('redis connect error');
        }
    }

    /**
     * set
     * @param $key
     * @param $value
     * @param int $time
     * @return bool|string
     */
    public function set($key, $value, $time = 0 ) {
        if(!$key) {
            return '';
        }
        if(is_array($value)) {
            $value = json_encode($value);
        }
        if(!$time) {
            return $this->redis->set($key, $value);
        }

        return $this->redis->setex($key, $time, $value);
    }

    /**
     * get
     * @param $key
     * @return bool|string
     */
    public function get($key) {
        if(!$key) {
            return '';
        }

        return $this->redis->get($key);
    }

    /**
     * @param $key
     * @return array
     */
    public function sMembers($key) {
        return $this->redis->sMembers($key);
    }

    /**
     * @param $name
     * @param $arguments
     * @return array
     */
    public function __call($name, $arguments) {
        //echo $name.PHP_EOL;
        //print_r($arguments);
        if(count($arguments) != 2) {
            return '';
        }
        $this->redis->$name($arguments[0], $arguments[1]);
    }
}


控制器中

<?php
namespace app\index\controller;
use app\commom\Ws;
use app\common\Client;

class Index
{
    public function aaa()
    {
        //连接swoole 服务
        $cli = new \swoole_client(SWOOLE_SOCK_TCP);

        //判断连接状态(同步连接模式)
        if ($cli->connect('127.0.0.1', 9502)) {
              echo "成功".PHP_EOL;
        } else {
              echo "失败";
        }
        $name='终于成功了,累死我了!';

        //发送消息给server
        $aaa=$cli->send($name);
        echo $aaa.PHP_EOL;
        echo '你er大爷的'.PHP_EOL;
    }
}

 

 

结果展示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值