thinkphp5结合swoole,进行websocket编程

namespace app\index\controller;
   use think\Db;
   use think\Config;
   class Swooletest {
   public function __construct(){
           $this->redis = new \Redis();
           $this->redis->connect('127.0.0.1',6379);
   }
   public function index() {
       $this->server = new \swoole_websocket_server('127.0.0.1',9502);
       $this->server->addlistener('0.0.0.0', 9503, SWOOLE_SOCK_UDP);
       $this->server->on('Open',[$this, 'onOpen']);
       $this->server->on('Message', [$this, 'onMessage']);
       $this->server->on('packet', [$this, 'Packet']);
       $this->server->on('Close', [$this, 'onClose']);
       $this->server->start();
   }
   public function onOpen(\swoole_websocket_server $server, \swoole_http_request $request) {
       $server->push($request->fd, $this->ajaxReturn(1,'success',['method'=>'connect']));
   }
   public function onMessage(\swoole_websocket_server $server, \swoole_websocket_frame $frame){
       $data = json_decode($frame->data,true);
       $method = isset($resive_data['method']) ? $resive_data['method'] : '' ;
       echo $method;
       switch ($method) {
           case 'join':
           //逻辑代码
           break;
       default:
           break;
       }
   }
   //接收UDP消息
   public function Packet(\swoole_websocket_server $server, $data_string, $addr) {
       $data = json_decode($data_string,true);
      //逻辑代码
       $server->push($login_data['fd'], $this->ajaxReturn(1,"success",['method'=>'verify','fd'=>$login_data['fd']]));
   }
   public function onClose($server, $fd) {

   }

}


swoole大部分功能需运行在cli模式下,以代码需 linux环境下运行/usr/local/php/bin/php index.php /Swooletest/index命令
以下代码是app扫码,请求后端,后端UDP广播,websocket发送h5登录成功通知


namespace app\api\controller;
use think\Db;
use think\Lang;    
class Udp extends Base
{
   public function __construct() {
       parent::__construct();
       $this->ip = '127.0.0.1';
       $this->port = '9503';
   }
   public function index() {
      //逻辑代码
      //api接口扫码后发送请求,处理登录,发送UDP通知,无需cli模式
       $data = ['type'=>$type];
       $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
       $msg = json_encode($data);
       $len = strlen($msg);
       socket_sendto($sock, $msg, $len, 0, $this->ip, $this->port);
       socket_close($sock);
   }
}


2017.3.21   /   热度:2497   /   分类: php

发表评论:

©地球仪的BLOG  |  Powered by Emlog