// +---------------------------------------------------------------------- // | Date: 2020-9-28 10:55:00 // +---------------------------------------------------------------------- namespace bw\gatewayworker; use GatewayClient\Gateway; /** gatewayworker 客户端 composer require workerman/gatewayclient , composer require textalk/websocket * Class Client * @package app\bwmall\model */ class Client { protected $identity = ''; protected $data = []; protected $token_data = []; protected $entity = null; protected $config = []; protected $connection = null; public function __construct($identity = '',$param=[]) { $this->identity = $identity; $this->data = $param; $identify = "\\bw\\gatewayworker\\" . ucfirst(camelize($this->identity)); if (!class_exists($identify)) { // 连接身份不存在 } $this->config['register_address'] = config('site.gateway_register_address'); $this->entity = new $identify($this, $this->data); $this->token_data = $this->entity()->getToken($this->data); //发起连接 $this->connection(); } public function __destruct(){ $this->closeConnection(); } public function closeConnection(){ if($this->connection) $this->connection->close(); return $this; } public function setConfig($options=[]){ $this->config = array_merge($this->config,$options); return $this; } public function connection($options=[]){ $this->setConfig($options); $live_play_socket = $this->config['register_address']; $params = $this->token_data ? '?'.http_build_query($this->token_data) : ''; $url=$live_play_socket.$params; //服务地址 $this->connection = new \WebSocket\Client($url); //实例化\ return $this; } public function message($method, $parameters){ $res= $this->entity()->{$method}(...$parameters); $this->connection->send(json_encode($res)); //发送数据 // var_dump(json_encode($res)); return $this; //接收数据 } public function entity() { return $this->entity; } // 代理身份相关的方法 public function __call($method, $parameters) { return $this->entity()->{$method}(...$parameters); } }