Home PHP Framework Swoole Basic steps to build swoole service under Linux

Basic steps to build swoole service under Linux

Nov 22, 2019 pm 04:15 PM
linux swoole build Serve

Basic steps to build swoole service under Linux

1. Install swoole service

1. Download the swoole source code, download address: https://github.com/swoole/swoole-src/releases

2. Upload the tar package to /usr/local/src/swoole, where the installation source files are stored.

3. Decompress the source file, tar –xvfswoole.tar

4. Enter the directory you just decompressed and enter the command phpize

5. Note: phpize is php-devel It can dynamically add extensions to PHP, so please make sure the php-devel package is installed on your machine.

6. Then, enter the following commands in sequence: ./configure, execute the compilation and detection make, and compile swoole

7. The pcre and pcre-devel related software packages are missing, just install them.

8.sudo make install

9.php.ini is generally compiled and installed under etc. After successful installation, we also need to modify php.ini and add the swoole.so extension to it:

10.extension=swoole.so

11. Enter php -m and you can see swoole, indicating that the extension is installed successfully.

2. Install apache and start the swoole service

(1) Test whether the installation is correct and start the swoole Php service

(2) Add the server.php file in apache, and client .php files. The general directory is under var/www/html

(3) Open two terminals. Open these two files under the directory where these two files are located to achieve socket long connection service.

Install lsof: yum -y install lsof

3. Configure the server side

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]);
    }
}
Copy after login

4. Configure the html front-end

$(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);
    }
});
Copy after login

5. Start start.php file, cd to the specified directory, and then PHP-CLI runs php start.php. In this method, thread protection is not enabled and the thread is still occupied after the program ends.

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

PHP Chinese website, a large number of free swoole introductory tutorials, welcome to learn online!

The above is the detailed content of Basic steps to build swoole service under Linux. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use docker desktop How to use docker desktop Apr 15, 2025 am 11:45 AM

How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

How to view the docker process How to view the docker process Apr 15, 2025 am 11:48 AM

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

What to do if the docker image fails What to do if the docker image fails Apr 15, 2025 am 11:21 AM

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

vscode cannot install extension vscode cannot install extension Apr 15, 2025 pm 07:18 PM

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

How to back up vscode settings and extensions How to back up vscode settings and extensions Apr 15, 2025 pm 05:18 PM

How to back up VS Code configurations and extensions? Manually backup the settings file: Copy the key JSON files (settings.json, keybindings.json, extensions.json) to a safe location. Take advantage of VS Code synchronization: enable synchronization with your GitHub account to automatically back up all relevant settings and extensions. Use third-party tools: Back up configurations with reliable tools and provide richer features such as version control and incremental backups.

See all articles