搜索
首页php框架SwooleLinux下搭建swoole服务的基本步骤

Linux下搭建swoole服务的基本步骤

Nov 22, 2019 pm 04:15 PM
linuxswoole搭建服务

Linux下搭建swoole服务的基本步骤

一、安装swoole服务

1.下载swoole源码,下载地址: https://github.com/swoole/swoole-src/releases

2.将tar包上传到/usr/local/src/swoole下面,这里面存储安装源文件。

3.解压源文件,tar –xvfswoole.tar

4.进入到刚解压的目录下输入命令phpize

5.注意:phpize是php-devel中的东西,它可以给PHP动态添加扩展,所以,请确保你的机器上安装了php-devel软件包。

6.接着,依次输入如下命令:./configure,执行编译检测make,编译swoole

7.缺少pcre和pcre-devel相关软件包,安装上即可。

8.sudo make install

9.php.ini一般在etc下面 编译安装成功后,我们还需要修改php.ini,在其中加入swoole.so扩展:

10.extension=swoole.so

11.输入php -m中能查看到swoole说明扩展安装成功。

二、安装apache启动swoole服务

(1)测试是否安装正确启动swoole Php服务

(2)在apache中添加server.php文件,和client.php文件。一般目录在var/www/html下面

(3)打开两个终端 在这两个文件所在的目录下面打开这两个文件,可以实现socket长连接服务。

安装lsof:yum -y install lsof

三、配置Server端

class WebSocketService {
 
   private static $instance = NULL;
   public $tagindex = 0;
   public    $server    = null;
   public   $office_cache = null;
   public    $timer_arr = [];    //该变量保存所有的定时器任务ID,每一个客户端可以通过$timer_arr[客户端ID]
   得到该客户端建立的所有定时器
   public $conf      = [
       'host'            => '0.0.0.0',
       'port'            => 9999,     //服务使用端口
       'worker_num'      => 2,         //启动worker进程数
       'task_worker_num' => 8,           //启动task进程数
       'is_daemonize'    => 0,          //是否后台运行:0-否,1-是
       'log_file'        =>'/tmp/swoole_webSocket_server.log',    //日志文件路径
       'abc'              =>0,
   ];
 
   public function getTagIndex() {
       return $this->conf['abc'];
    }
 
   public function setSetTagIndex($index) {
       $this->conf['abc'] = 100;
       echo $this->getTagIndex();
    }
 
   public function __construct($config = []) {
       $this->office_cache = array('1' => '1', '3'=>'2');
       $this->conf = array_merge($this->conf, (array)$config);
    }
 
   //静态方法,返回此类唯一实例 
   public static function getInstance(){
       if(empty(self::$instance)){ 
           echo "instance \n";
           self::$instance=new WebSocketService(); 
       } 
       return self::$instance; 
    }
 
   /**
    * 服务器端运行webSocket的入口
    */
   public function run() {
       try {
           $this->server = new \swoole_websocket_server($this->conf['host'],$this->conf['port']);
           $this->server->set(
                [
                    'worker_num'      => $this->conf['worker_num'],
                    'task_worker_num' =>$this->conf['task_worker_num'],
                    'daemonize'       => $this->conf['is_daemonize'],
                    'log_file'        => $this->conf['log_file'],
                ]
           );
 
           //注册方法列表
           $this->server->on('open', [$this, 'open']);
           $this->server->on('message', [$this, 'message']);
           $this->server->on('task', [$this, 'task']);
           $this->server->on('finish', [$this, 'finish']);
           $this->server->on('close', [$this, 'close']);
 
           $this->server->start();
       } catch (\Exception $e) {
           var_dump($e->getCode() . ':' . $e->getMessage());
       }
 
    }
 
   /**
    * 建立socket链接时,执行方法
    * @param $server
    * @param $request
    */
   public function open($server, $request) {
       $data = [
           'client_id' => $request->fd,
           'request'   => $request
       ];
       echo &#39;open<<&#39;.$data[&#39;client_id&#39;];
       $this->doOpen($data);
    }
 
   /**
    * 发送消息时,执行方法
    * @param $server
    * @param $frame
    */
   public function message($server, $frame) {
       echo "GET_mesage\n";
       $data = [
           &#39;client_id&#39; => $frame->fd,
           &#39;data&#39;      => $frame->data,
           &#39;frame&#39;     => $frame,
       ];
       $this->doMessage($data);
    }
 
   /**
    * 执行具体任务
    * @param $server
    * @param $task_id
    * @param $from_id
    * @param $data
    */
   public function task($server, $task_id, $from_id, $data) {
       $data[&#39;task_id&#39;] = $task_id;
       $data[&#39;from_id&#39;] = $from_id;
       $this->doTask($data);
    }
 
   /**
    * 任务结果处理
    * @param $server    服务器对象
    * @param $taskId    任务进程ID
    * @param $data
    */
   public function finish($server, $taskId, $data) {
       $data[&#39;task_id&#39;] = $taskId;
       $this->doFinish($data);
    }
 
   /**
    * 关闭链接
    * @param $server        服务器对象
    * @param $client_id     客户端唯一标识
    */
   public function close($server, $client_id) {
       $data = [
           &#39;client_id&#39; => $client_id
       ];
       $this->doClose($data);
    }
 
   /**
    * 客户端成功连接到服务器时,会触发该方法
     * 子类根据需求重写该方法
    * @param $data
    * [
    *    &#39;client_id&#39;,    //客户端唯一标识
    *    &#39;data&#39;,        //一些请求数据
    *    &#39;frame&#39;,        //swoole的数据
    * ];
    */
   public function doOpen($data) {
       echo "建立连接成功";
 
    }
 
   /**
    * 得到Swoole Websocket Server
    *
    * @return null|\swoole_websocket_server
    */
   public function getServer()
    {
       return $this->server;
    }
 
   /**
    * 收到客户端发来的消息,会触发该方法
    * 子类根据需求重写该方法
    * @param $data
    * [
    *    &#39;client_id&#39;,    //客户端唯一标识
    *    &#39;data&#39;,        //客户端发送过来的消息(数据)
    *    &#39;frame&#39;,        //swoole的数据
    * ];
    */
   public function doMessage($data) {
       $info = json_decode($data[&#39;data&#39;],true);
       $officeid = $info[&#39;officeid&#39;];
       $client_id = $data[&#39;client_id&#39;];
       echo"<<<<".$officeid.">>>>".$client_id."\r\n";
       if ($officeid == 1) {
           $this->sendMsgToClient(&#39;2&#39;,array(&#39;msg&#39; =>&#39;我是1号场地发送给你数据&#39;));
       } else {
           $this->sendMsgToClient(&#39;1&#39;,array(&#39;msg&#39; =>&#39;我是3号场地发送给你数据&#39;));
       }
    }
 
   /**
    * 具体的工作任务。需要通过 $this->doJob()来触发
    * 子类根据需求重写该方法
    * @param $data
    * [
    *    &#39;client_id&#39;,    //客户端唯一标识
    * ];
    */
   public function doTask($data) {
    }
 
   /**
    * 工作的结果处理。
     * 子类根据需求重写该方法
    * @param $data
    * [
    *    &#39;client_id&#39;,    //客户端唯一标识
    * ];
    */
   public function doFinish($data) {
    }
 
   /**
    * 客户端断开时会自动触发该方法
    * 子类根据需求重写该方法
    * @param $data
    * [
    *    &#39;client_id&#39;,    //客户端唯一标识
    * ];
    */
   public function doClose($data) {
    }
 
 
   /**
    * 发送任务
    * @param $data    必须是数组,且要有$data[&#39;client_id&#39;]
    */
   public function doJob($data) {
       $this->server->task($data);
    }
 
   public function finishJob($data) {
       $this->server->finish($data);
    }
 
   /**
    * 发送消息到客户端
    * @param $client_id
    * @param $msg
    */
   public function sendMsgToClient($client_id, $msg) {
       echo "发送信息给客户端:{$client_id} | {$msg[&#39;action&#39;][&#39;name&#39;]} | " . date(&#39;Y-m-dH:i:s&#39;) . "\r\n";
       $this->server->push($client_id, json_encode($msg));
    }
 
   /**
    * 关闭客户端链接
    * @param $client_id
    */
   public function closeClient($client_id) {
       $this->server->close($client_id);
    }
 
   /**
    * 添加定时器
    * @param $client_id
    * @param $tick_time
    */
   public function addTimer($client_id, $tick_time) {
       //暂未实现,先使用swoole原生写法
    }
 
   /**
    * 清除定时器
    * @param $client_id
    * @param $arr
    */
   public function clearTimer($client_id, &$arr) {
       if (is_array($arr)) {
           foreach ($arr[$client_id] as $val) {
                if (is_array($val)) {
                    foreach ($val as $v) {
                        swoole_timer_clear($v);
                    }
                } else {
                    swoole_timer_clear($val);
                }
           }
       }
       unset($arr[$client_id]);
    }
}

四、配置html前端

$(document).ready(function(){
    varwsurl = "ws://182.92.101.206:9999/";
    console.log(wsurl);
    varwebsocket = new WebSocket(wsurl);
    websocket.onopen= function(evt){
    console.log(&#39;Server:  打开WebSocket连接&#39;);
    };

    websocket.onclose= function(evt){
           console.log(&#39;Server:  关闭WebSocket连接&#39;);
    };

    websocket.onmessage= function(evt){
           varres = JSON.parse(evt.data);
           console.log(&#39;Server:  收到消息(来自:&#39;+res+&#39;请求)&#39;);
           console.log(res);
    };

    websocket.οnerrοr= function(evt){
           console.log(&#39;Server:  出现错误&#39;);
           console.log(evt.data);
    }

    functiondoSend(msg){
           console.log(&#39;Client:发送消息  &#39; + msg);
           websocket.send(msg);
    }
});

五、启动start.php文件,cd到指定目录下,然后PHP-CLI运行php start.php。这种方式是没有启用线程保护的关掉后程序结束线程还在占用。

require&#39;src/WebSocketSwoole/WebSocketService.php&#39;;
// require &#39;./WebSocketService.php&#39;;
session_start();
// $demoService = new\WebSocketSwoole\WebSocketService();
$demoService =\WebSocketSwoole\WebSocketService::getInstance();
$demoService->run();

PHP中文网,大量的免费swoole入门教程,欢迎在线学习!

以上是Linux下搭建swoole服务的基本步骤的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:CSDN。如有侵权,请联系admin@php.cn删除

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版