Home >PHP Framework >Swoole >Swoole Network Programming Basics Beginner's Guide
With the continuous development and popularization of the Internet, network programming technology has become one of the necessary skills for many programmers. In this field, Swoole is a very excellent network communication framework. Swoole is an extension module of PHP that provides powerful network programming functions such as asynchronous IO, multi-process, and coroutine, and can well solve problems such as high concurrency and high performance. This article will introduce you to Swoole's basic introductory guide to network programming.
1. Installation and configuration of Swoole
The installation of Swoole requires PHP version greater than 7.0, and phpize and php-config need to be installed. You can install it through the following command:
$ git clone https://github.com/swoole/swoole-src.git $ cd swoole-src $ phpize $ ./configure $ make && make install
After the installation is complete, add the following configuration in php.ini:
extension=swoole.so
2. Basic use of Swoole
1. Create a TCP server
Swoole can be created with the following code A TCP server, listening to the 9501 port of the local machine:
$server = new SwooleServer("0.0.0.0", 9501);
2. Monitoring events
The server needs to monitor the client's connection, receive data, close the connection and other events. You can listen through the following code:
$server->on('connect', function ($serv, $fd) { echo "Client: connect. "; }); $server->on('receive', function ($serv, $fd, $from_id, $data) { $serv->send($fd, "Server: ".$data); }); $server->on('close', function ($serv, $fd) { echo "Client: close. "; });
In the above code, the on method is used to bind the event name and callback function.
3. Start the server
After completing the event monitoring, you need to run the following code to start the server:
$server->start();
At this point, a TCP server has been successfully created. It can be tested through tools such as telnet.
3. Create a UDP server
Swoole can also create a UDP server, and its usage is similar to that of a TCP server. The following is a sample code for creating a UDP server:
$server = new SwooleServer("0.0.0.0", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_UDP); $server->on('Packet', function ($server, $data, $clientInfo) { $server->sendto($clientInfo['address'], $clientInfo['port'], "Server ".$data); }); $server->start();
In the above code, a UDP server is created to listen to the 9502 port of the local machine. When data is sent to the server, the Packet event is triggered and the data is sent back to the client.
4. Create a WebSocket server
Swoole can also create a WebSocket server. WebSocket is a full-duplex communication protocol based on the TCP protocol. The following is a sample code for creating a WebSocket server:
$server = new SwooleWebSocketServer("0.0.0.0", 9503); $server->on('open', function (SwooleWebSocketServer $server, $request) { echo "server: handshake success with fd{$request->fd} "; }); $server->on('message', function (SwooleWebSocketServer $server, $frame) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish} "; $server->push($frame->fd, "this is server"); }); $server->on('close', function ($ser, $fd) { echo "client {$fd} closed "; }); $server->start();
In the above code, a WebSocket server is created and listens to the 9503 port of the local machine. When a client connects, the open event is triggered. When a client sends a message, the message event is triggered and the message is sent back to the client as is. When a client closes the connection, the close event is triggered.
3. Advanced use of Swoole
1. Use Task asynchronous tasks
The Task function provided by Swoole can process some time-consuming business logic asynchronously without blocking. The running of the main process. The following is a sample code for Task:
$server = new SwooleServer("0.0.0.0", 9501); $server->on('receive', function ($serv, $fd, $from_id, $data) { $task_id = $serv->task($data); //投递异步任务 echo "Dispath AsyncTask: id=$task_id "; }); $server->on('task', function ($serv, $task_id, $from_id, $data) { echo "New AsyncTask[id=$task_id]".PHP_EOL; // 处理异步任务 $serv->finish("$data -> OK"); }); $server->on('finish', function ($serv, $task_id, $data) { echo "AsyncTask[$task_id] Finish: $data".PHP_EOL; }); $server->start();
In the above sample code, when a client sends data to the server, the task will be delivered to the Task queue and the asynchronous task will be processed in the onTask event. After the Task processing is completed, the onFinish event will be called to return the processing results to the client.
2. Using coroutines
Coroutines are a concurrent programming method provided by Swoole, which can achieve tens of millions of levels of concurrent processing in one thread. The following is a sample code for using coroutine:
Coun(function () { $client = new SwooleCoroutineClient(SWOOLE_SOCK_TCP); if (!$client->connect('127.0.0.1', 9501, 0.5)) { echo "connect failed. Error: {$client->errCode} "; } $client->send("hello swoole"); $res = $client->recv(); echo $res; $client->close(); });
In the above sample code, a coroutine task is created using Coun, a TCP client is created through SwooleCoroutineClient, and the connect method is used to connect. When the connection is successfully established, use the send method to send a message and use the recv method to receive the return result. Finally, use the close method to close the connection.
4. Summary
This article introduces the basic usage of the Swoole network programming framework, and demonstrates the functions of TCP server, UDP server, WebSocket server, Task asynchronous task, coroutine and other functions through sample code How to use. Swoole has flexibility and high performance, and can achieve excellent results in many scenarios. However, developers are also required to have certain underlying knowledge and targeted programming thinking. I believe that readers can have a preliminary understanding and application of Swoole through the introduction of this article.
The above is the detailed content of Swoole Network Programming Basics Beginner's Guide. For more information, please follow other related articles on the PHP Chinese website!