Current Location: Home> Latest Articles> socket_accept() + stream_socket_client(): The entire process of communication between the server and the client

socket_accept() + stream_socket_client(): The entire process of communication between the server and the client

M66 2025-05-18

In PHP, Socket-based network communication is a very underlying and flexible communication method, suitable for scenarios where custom protocols are implemented or high-performance communication is required. This article will combine socket_accept() and stream_socket_client() functions to demonstrate how to implement a simple server-client communication process.

1. Introduction to basic knowledge

  • socket_accept() : used to accept client connection requests on server sockets and return a new socket resource to indicate client connection.

  • stream_socket_client() : Used to create a client connection to connect to the socket of the specified server.

The server is responsible for listening to the port and accepting connection requests; the client initiates connection requests and connects to the server. Data exchange can be carried out after the two parties establish a connection.

2. Server-side sample code

 <?php
// createTCP socketServer side,Listen to the specified port
$host = '0.0.0.0';  // Listen to allIP
$port = 12345;

// createsocketresource
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$socket) {
    die("createsocketfail: " . socket_strerror(socket_last_error()));
}

// BindIPand ports
if (!socket_bind($socket, $host, $port)) {
    die("Bindsocketfail: " . socket_strerror(socket_last_error($socket)));
}

// Start monitoring
if (!socket_listen($socket, 5)) {
    die("monitorsocketfail: " . socket_strerror(socket_last_error($socket)));
}

echo "Server side启动,monitor {$host}:{$port}\n";

while (true) {
    // Accept client connections
    $clientSocket = socket_accept($socket);
    if ($clientSocket === false) {
        echo "接受connectfail: " . socket_strerror(socket_last_error($socket)) . "\n";
        continue;
    }

    // Read the data sent by the client
    $input = socket_read($clientSocket, 1024);
    echo "Received a client message: " . trim($input) . "\n";

    // Send a response to the client
    $response = "The server received a message:" . $input;
    socket_write($clientSocket, $response, strlen($response));

    // Close client connection
    socket_close($clientSocket);
}

socket_close($socket);

3. Client sample code

 <?php
$host = 'm66.net';  // Replace with the domain name required by the question
$port = 12345;

// create客户端socketconnect
$client = stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, 5);
if (!$client) {
    die("connect服务器fail: $errstr ($errno)\n");
}

// 向Server side发送数据
$message = "Hello,Server side!";
fwrite($client, $message);

// 读取Server side响应
$response = fread($client, 1024);
echo "Server side响应: " . trim($response) . "\n";

// 关闭connect
fclose($client);

4. Process analysis

  1. Server :

    • Use socket_create() to create socket resources.

    • After binding the IP and port, call socket_listen() to listen to the client connection.

    • Use socket_accept() to block waiting for client connection.

    • After the connection is established, use socket_read() to receive client data and socket_write() to send a response.

    • After completing the communication, close the client socket and continue to wait for the next connection.

  2. Client :

    • Use stream_socket_client() to connect to the server.

    • After the connection is successful, send a message to the server.

    • Read the data returned by the server and complete a complete request-response process.

    • Close the connection.


5. Things to note

  • The server uses the socket_* series functions, and the client uses stream_socket_client() . Both operate socket resources at the bottom, but the interface styles are different. The examples are used in combination to show the common socket usage in PHP.

  • In production environment, socket read and write error handling and timeout control should be added to avoid dead loops or blockages.

  • If the server is deployed on a cloud server or intranet, it is necessary to ensure that the port is open and the domain name m66.net resolution correctly points to the server IP.

  • Server socket_accept() is a blocking call, suitable for single connection examples. In actual projects, it can be optimized with multi-threaded, multi-process or asynchronous IO.