Home > Article > Backend Development > PHP development: How to use Swoft to implement TCP server
In network programming, TCP is an important protocol. In PHP, implementing the TCP server can not only improve the efficiency of network programming, but also learn from this model to implement some network applications. This article will introduce how to use the Swoft framework to quickly implement a TCP server.
Swoft is a PHP high-performance coroutine network framework based on the Swoole extension. It implements coroutines similar to the Go language, greatly improving the performance of PHP network programming. and efficiency.
Swoft has the following characteristics:
Before using the Swoft framework to implement the TCP server, you need to install the following tools:
First, use the Composer tool to create a Swoft project:
composer create-project swoft/swoft swoft-project
In the ## of the project Create a TcpController.php
file in the #app/Controller directory with the following content:
namespace AppController; use SwoftHttpMessageRequest; use SwoftHttpMessageResponse; use SwoftTcpServerAnnotationMappingTcpController; use SwoftTcpServerAnnotationMappingTcpMapping; /** * @TcpController() */ class TcpController { /** * @TcpMapping("echo") */ public function echo(Request $request) { $params = $request->getParams(); return $params['msg'] . " "; } }In the controller, we define an
echo method, This method accepts the data sent by the client and returns the same message.
TcpServer.php file in the
app/Server directory of the project, which is Start the entrance of the TCP server, the content is as follows:
namespace AppServer; use SwoftBeanAnnotationMappingBean; use SwoftLogHelperCLog; use SwoftTcpServerAnnotationMappingTcpServer; use SwoftTcpServerRequest; /** * @Bean() * @TcpServer(port=9999) */ class TcpServer { public function onReceive(Request $request) { $params = $request->getParams(); $msg = $params['data']; CLog::info('receive data:%s', $msg); $response = "received:" . $msg; return $response; } }In
TcpServer, we specify the port through the
@TcpServer annotation, and implement the
onReceive method Accept the data sent by the client. In this method, we can forward the request to the specified controller to complete the business logic.
php bin/swoft tcp:startIn another terminal, use telnet to connect to the TCP server Test:
telnet localhost 9999 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. {"method":"echo","params":{"msg":"hello, swoft!"}} hello, swoft! Connection closed by foreign host.The client sends a piece of data in JSON format to the server. The server parses the data and calls the
echo method to return the same data. The client prints the received data. data and exit the connection.
The above is the detailed content of PHP development: How to use Swoft to implement TCP server. For more information, please follow other related articles on the PHP Chinese website!