In the company's business, the chat system uses the swoole framework. This framework is a PHP extension written in C language and is very convenient to use!
1 The installation process is very simple (no introduction is required)
2 Let’s take a look at the example copied from the official website document. I wrote the comments in detail
<code><span>// Server</span><span><span>class</span><span>Server</span> {</span><span>private</span><span>$serv</span>; <span>//构造函数</span><span>public</span><span><span>function</span><span>__construct</span><span>()</span> {</span><span>//新建一个对象,接收所有的ip链接,端口设置为9501</span><span>$this</span>->serv = <span>new</span> swoole_server(<span>"0.0.0.0"</span>, <span>9501</span>); <span>$this</span>->serv->set(<span>array</span>( <span>'worker_num'</span> => <span>8</span>, <span>//设置work进程的数量为8</span><span>'daemonize'</span> => <span>false</span>,<span>//设置为后台进程</span><span>'max_request'</span> => <span>10000</span>, <span>//每个worker进程允许处理的最大任务数</span><span>'dispatch_mode'</span> => <span>2</span>, <span>'debug_mode'</span>=> <span>1</span> )); <span>$this</span>->serv->on(<span>'Start'</span>, <span>array</span>(<span>$this</span>, <span>'onStart'</span>));<span>//设置回调函数 onstart</span><span>$this</span>->serv->on(<span>'Connect'</span>, <span>array</span>(<span>$this</span>, <span>'onConnect'</span>)); <span>$this</span>->serv->on(<span>'Receive'</span>, <span>array</span>(<span>$this</span>, <span>'onReceive'</span>)); <span>$this</span>->serv->on(<span>'Close'</span>, <span>array</span>(<span>$this</span>, <span>'onClose'</span>)); <span>$this</span>->serv->start(); } <span>public</span><span><span>function</span><span>onStart</span><span>( <span>$serv</span> )</span> {</span><span>echo</span><span>"Start\n"</span>; } <span>public</span><span><span>function</span><span>onConnect</span><span>( <span>$serv</span>, <span>$fd</span>, <span>$from_id</span> )</span> {</span><span>$serv</span>->send( <span>$fd</span>, <span>"Hello {$fd}!"</span> ); } <span>public</span><span><span>function</span><span>onReceive</span><span>( swoole_server <span>$serv</span>, <span>$fd</span>, <span>$from_id</span>, <span>$data</span> )</span> {</span><span>echo</span><span>"Get Message From Client {$fd}:{$data}\n"</span>; } <span>public</span><span><span>function</span><span>onClose</span><span>( <span>$serv</span>, <span>$fd</span>, <span>$from_id</span> )</span> {</span><span>echo</span><span>"Client {$fd} close connection\n"</span>; } } <span>// 启动服务器</span><span>$server</span> = <span>new</span> Server();</code>
A. Create the swoole_server object through the constructor
B. Call the set function to set the relevant configuration options of swoole_server
C. Call the on function to set the relevant callback function. Specific instructions on the set configuration options and the on callback function
The above has introduced swoole 1, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.