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 'open<<'.$data['client_id']; $this->doOpen($data); } /** * 发送消息时,执行方法 * @param $server * @param $frame */ public function message($server, $frame) { echo "GET_mesage\n"; $data = [ 'client_id' => $frame->fd, 'data' => $frame->data, 'frame' => $frame, ]; $this->doMessage($data); } /** * 执行具体任务 * @param $server * @param $task_id * @param $from_id * @param $data */ public function task($server, $task_id, $from_id, $data) { $data['task_id'] = $task_id; $data['from_id'] = $from_id; $this->doTask($data); } /** * 任务结果处理 * @param $server 服务器对象 * @param $taskId 任务进程ID * @param $data */ public function finish($server, $taskId, $data) { $data['task_id'] = $taskId; $this->doFinish($data); } /** * 关闭链接 * @param $server 服务器对象 * @param $client_id 客户端唯一标识 */ public function close($server, $client_id) { $data = [ 'client_id' => $client_id ]; $this->doClose($data); } /** * 客户端成功连接到服务器时,会触发该方法 * 子类根据需求重写该方法 * @param $data * [ * 'client_id', //客户端唯一标识 * 'data', //一些请求数据 * 'frame', //swoole的数据 * ]; */ public function doOpen($data) { echo "建立连接成功"; } /** * 得到Swoole Websocket Server * * @return null|\swoole_websocket_server */ public function getServer() { return $this->server; } /** * 收到客户端发来的消息,会触发该方法 * 子类根据需求重写该方法 * @param $data * [ * 'client_id', //客户端唯一标识 * 'data', //客户端发送过来的消息(数据) * 'frame', //swoole的数据 * ]; */ public function doMessage($data) { $info = json_decode($data['data'],true); $officeid = $info['officeid']; $client_id = $data['client_id']; echo"<<<<".$officeid.">>>>".$client_id."\r\n"; if ($officeid == 1) { $this->sendMsgToClient('2',array('msg' =>'我是1号场地发送给你数据')); } else { $this->sendMsgToClient('1',array('msg' =>'我是3号场地发送给你数据')); } } /** * 具体的工作任务。需要通过 $this->doJob()来触发 * 子类根据需求重写该方法 * @param $data * [ * 'client_id', //客户端唯一标识 * ]; */ public function doTask($data) { } /** * 工作的结果处理。 * 子类根据需求重写该方法 * @param $data * [ * 'client_id', //客户端唯一标识 * ]; */ public function doFinish($data) { } /** * 客户端断开时会自动触发该方法 * 子类根据需求重写该方法 * @param $data * [ * 'client_id', //客户端唯一标识 * ]; */ public function doClose($data) { } /** * 发送任务 * @param $data 必须是数组,且要有$data['client_id'] */ 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['action']['name']} | " . date('Y-m-dH:i:s') . "\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]); } }
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('Server: 打开WebSocket连接'); }; websocket.onclose= function(evt){ console.log('Server: 关闭WebSocket连接'); }; websocket.onmessage= function(evt){ varres = JSON.parse(evt.data); console.log('Server: 收到消息(来自:'+res+'请求)'); console.log(res); }; websocket.οnerrοr= function(evt){ console.log('Server: 出现错误'); console.log(evt.data); } functiondoSend(msg){ console.log('Client:发送消息 ' + msg); websocket.send(msg); } });
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'src/WebSocketSwoole/WebSocketService.php'; // require './WebSocketService.php'; session_start(); // $demoService = new\WebSocketSwoole\WebSocketService(); $demoService =\WebSocketSwoole\WebSocketService::getInstance(); $demoService->run();
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!

linux设备节点是应用程序和设备驱动程序沟通的一个桥梁;设备节点被创建在“/dev”,是连接内核与用户层的枢纽,相当于硬盘的inode一样的东西,记录了硬件设备的位置和信息。设备节点使用户可以与内核进行硬件的沟通,读写设备以及其他的操作。

区别:1、open是UNIX系统调用函数,而fopen是ANSIC标准中的C语言库函数;2、open的移植性没fopen好;3、fopen只能操纵普通正规文件,而open可以操作普通文件、网络套接字等;4、open无缓冲,fopen有缓冲。

端口映射又称端口转发,是指将外部主机的IP地址的端口映射到Intranet中的一台计算机,当用户访问外网IP的这个端口时,服务器自动将请求映射到对应局域网内部的机器上;可以通过使用动态或固定的公共网络IP路由ADSL宽带路由器来实现。

在linux中,eof是自定义终止符,是“END Of File”的缩写;因为是自定义的终止符,所以eof就不是固定的,可以随意的设置别名,linux中按“ctrl+d”就代表eof,eof一般会配合cat命令用于多行文本输出,指文件末尾。

在linux中,交叉编译是指在一个平台上生成另一个平台上的可执行代码,即编译源代码的平台和执行源代码编译后程序的平台是两个不同的平台。使用交叉编译的原因:1、目标系统没有能力在其上进行本地编译;2、有能力进行源代码编译的平台与目标平台不同。

在linux中,可以利用“rpm -qa pcre”命令判断pcre是否安装;rpm命令专门用于管理各项套件,使用该命令后,若结果中出现pcre的版本信息,则表示pcre已经安装,若没有出现版本信息,则表示没有安装pcre。

linux查询mac地址的方法:1、打开系统,在桌面中点击鼠标右键,选择“打开终端”;2、在终端中,执行“ifconfig”命令,查看输出结果,在输出信息第四行中紧跟“ether”单词后的字符串就是mac地址。

在linux中,rpc是远程过程调用的意思,是Reomote Procedure Call的缩写,特指一种隐藏了过程调用时实际通信细节的IPC方法;linux中通过RPC可以充分利用非共享内存的多处理器环境,提高系统资源的利用率。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
