Current Location: Home> Latest Articles> How to use PHP's socket_accept() function to achieve efficient concurrent client connection processing?

How to use PHP's socket_accept() function to achieve efficient concurrent client connection processing?

M66 2025-05-25

In PHP, the socket_accept() function is one of the key functions that implement socket server-based. It is used to accept client connection requests and is the core link in handling client connections when building network services. This article will introduce in detail how to use socket_accept() to achieve efficient and concurrent client connection processing, and combine sample code to show practical applications.

1. The basic role of socket_accept()

socket_accept() will take out a connected client socket from the listened socket and return a new socket resource for communication with the client. If there is no connection, block waiting. Simply put, it is the entrance for the server to accept client connections.

 $clientSocket = socket_accept($serverSocket);
if ($clientSocket === false) {
    echo "Accepting client connection failed: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "Accept the client connection successfully\n";
}

2. Challenges of concurrent connection processing

PHP itself is single-threaded. When using socket_accept() directly to process multiple connections, if the processing is not done, the server will block on a certain client, resulting in the inability to respond to other connection requests at the same time.

To solve this problem, commonly used solutions include:

  • Multi-process/multi-threading : Create child processes through pcntl_fork() to process each client.

  • Non-blocking mode & multiplexing : Poll multiple connections in a single thread in combination with socket_set_nonblock() and socket_select() .

  • Event-driven framework : Use third-party libraries such as ReactPHP to implement asynchronous IO.

This article focuses on multi-process methods and demonstrates how to use socket_accept() to efficiently handle concurrent clients.

3. Typical multi-process concurrent server example

The following example shows a simple multi-process server, where the main process is responsible for listening and receiving connections, and the child process is responsible for handling client requests.

 <?php
// create TCP socket
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($server, '0.0.0.0', 8080);
socket_listen($server);

echo "Server startup,Listen to port 8080...\n";

while (true) {
    // Accept client connections(block)
    $client = socket_accept($server);
    if ($client === false) {
        echo "socket_accept mistake: " . socket_strerror(socket_last_error()) . "\n";
        continue;
    }

    // createSubprocess processing client
    $pid = pcntl_fork();
    if ($pid == -1) {
        echo "无法create子进程\n";
        socket_close($client);
        continue;
    } elseif ($pid > 0) {
        // The parent process closes the client connection,Continue to monitor
        socket_close($client);
        // You can choose to wait for the child process or use signal processing to recover
    } else {
        // Subprocess processing client
        socket_close($server);  // Close the listening socket in the child process

        $msg = "Welcome to visit m66.net PHP server!\n";
        socket_write($client, $msg, strlen($msg));

        // Read client messages
        $input = socket_read($client, 2048);
        echo "Received a client message: $input\n";

        // Simple echo
        socket_write($client, "server已收到: " . $input);

        socket_close($client);
        exit(0);  // Subprocess exits
    }
}

Code parsing

  • Use socket_create to create a TCP socket, bind the port and listen.

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

  • Use pcntl_fork() to create a child process. The parent process closes the client socket and continues to listen. The child process is responsible for reading and writing client data.

  • Exit after the child process is finished to avoid zombie processes.

4. Optimization suggestions

  • Prevent zombie processes <br> The main process needs to recycle child processes through signal processing or periodic call of pcntl_waitpid() to prevent zombie processes from accumulating.

  • Non-blocking and multiplexing <br> Use socket_select() to implement multiplexing, which can listen to multiple clients in a single process at the same time to avoid process overhead.

  • Connection pool management <br> For large numbers of connections, connection pools and task queues can be designed to improve server stability.

  • Error handling and logging <br> Incorporating detailed error handling and logging in production environments can help troubleshoot problems.

5. Summary

Through socket_accept() combined with multi-process method, efficient concurrent client connection processing can be achieved. Although PHP itself is not good at high concurrent network programming, it can create timely responsive network services through reasonable design and system calls.

It should be noted that although the multi-process mode is simple and intuitive, it also has the disadvantage of high resource consumption. Combining non-blocking IO and event-driven frameworks is a more modern approach. Either way, socket_accept() is the basis for connection processing.