Home >Backend Development >PHP Tutorial >PHP uses examples to understand what Socket is
Please understand it based on the position of the Socket abstraction layer in the figure below. Socket is an intermediate software abstraction layer for communication between the application layer and the TCP/IP protocol suite. It is a set of interfaces. In the design pattern, it is a facade pattern, which encapsulates complex implementations behind interfaces and only provides a set of simple interfaces for users to call. In common programming languages, these interfaces are generally create, bind, listen, accept, write, read, close, connect, etc.
1. Rendering
2. Code
Server: Server.php
<?php set_time_limit(0); // 去掉时间限制 ob_implicit_flush(); // 开启强制刷新 // 1. 创建Socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 2. 绑定端口和IP socket_bind($socket, '127.0.0.1', 11279); // 3. 端口监听 socket_listen($socket); echo 'Server is listening!' . PHP_EOL; // 4. accept阻塞进程 $connect = socket_accept($socket); // 直到有连接进入,accept才会返回 echo 'Client [' . $connect . '] is accessing...' . PHP_EOL; // 5. 交互 socket_write($connect, 'Welcome, visitor! Now you can send message to the server.' . PHP_EOL); while ($connect) { // 获取请求 $request = socket_read($connect, 1024); echo 'Client ['. $connect .'] message: ' . $request; // 关闭连接 if($request == "bye" . PHP_EOL){ socket_shutdown($connect); break; } // 发送响应 $response = 'Your sended message: ' . $request; socket_write($connect, $response); } // 6. 销毁Socket socket_close($socket);
Client: client.php
<?php // 1. 创建Socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 2. 建立连接 $result = socket_connect($socket, '127.0.0.1', 11279); if($result === false){ socket_close($socket); die('Socket connect failed: ' . socket_strerror(socket_last_error($socket))); } // 3. 交互 while($result){ // 获取响应 $response = socket_read($socket, 1024); echo $response; // 发送请求 $request = fgets(STDIN); socket_write($socket, $request, 1024); // 关闭连接 if($request == "bye" . PHP_EOL){ socket_shutdown($socket); break; } } // 4.销毁Socket socket_close($socket);
The above is the detailed content of PHP uses examples to understand what Socket is. For more information, please follow other related articles on the PHP Chinese website!