Current Location: Home> Latest Articles> Share experience in socket_set_block in WebSocket service

Share experience in socket_set_block in WebSocket service

gitbox 2025-05-29

Because of its two-way real-time communication, WebSocket technology is widely used in online chat, real-time push, game interaction and other scenarios. The performance and stability of network communications become key when building WebSocket services using PHP. The socket_set_block function, as an important tool in PHP socket programming, can help us effectively control the blocking and non-blocking state of the socket, thereby optimizing the response speed and resource utilization of WebSocket services.

This article will combine practical project experience to explain in depth how to efficiently use socket_set_block function in WebSocket service, and share some practical skills.


1. What is socket_set_block?

socket_set_block is a function provided by PHP to set whether the socket is in blocking mode. In blocking mode, socket operations (such as read or write) will wait for the operation to complete before returning; in non-blocking mode, the operation will return immediately, and if no data is available, an error will be returned.

 <?php
// set up socket In blocking mode
socket_set_block($socket);

// set up socket In non-blocking mode
socket_set_nonblock($socket);
?>

In WebSocket services, the choice of blocking and non-blocking has a huge impact on performance.


2. Blocking vs. non-blocking in WebSocket service

  • Blocking mode <br> Suitable for simple scenarios, the code flow is intuitive, but it may cause process lag, especially when the client responds slowly, the server may be "dragged" by a connection.

  • Non-blocking mode <br> Allows the server to return immediately and continues to process other tasks, which is more suitable for high-concurrency and multi-connection environments. However, the programming complexity increases, and it is necessary to combine polling (such as socket_select ) or event-driven models.


3. Efficiently manage connections with socket_set_block

In actual projects, my experience is to adopt the "flexible switch" strategy:

  • Connection establishment phase : Set socket to block to ensure that the connection handshake is completed reliably.

  • Data transmission stage : Switch to non-blocking, and combine socket_select to poll and listen to multiple connections to avoid performance bottlenecks caused by blocking.

Sample code snippet:

 <?php
$serverSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($serverSocket, '0.0.0.0', 9501);
socket_listen($serverSocket);

socket_set_block($serverSocket);

while (true) {
    $clientSocket = socket_accept($serverSocket);
    if ($clientSocket !== false) {
        // Complete the handshake,set up非阻塞模式,Begin asynchronous processing
        socket_set_nonblock($clientSocket);

        // Will $clientSocket Add to the client list,Use subsequently socket_select deal with
        $clients[] = $clientSocket;
    }

    // use socket_select Listen to multiple clients,Avoid blockage
    $read = $clients;
    $write = null;
    $except = null;
    if (socket_select($read, $write, $except, 0, 200000) > 0) {
        foreach ($read as $readSocket) {
            $data = socket_read($readSocket, 2048);
            if ($data === false || $data === '') {
                // Connection closed or error,Clean up resources
                $index = array_search($readSocket, $clients);
                unset($clients[$index]);
                socket_close($readSocket);
            } else {
                // deal with WebSocket Data frames
                // ...
            }
        }
    }
}
?>

4. Common pitfalls and optimization suggestions

  • Avoid long-term blocking : Call socket_read in blocking mode. If the client does not respond, the process may hang. It is recommended to combine timeout control or switch non-blocking as early as possible.

  • Reasonable use of socket_select : In combination with non-blocking mode, the server can handle a large number of connections at the same time and improve throughput.

  • Error handling should be detailed : In non-blocking mode, socket_read may return an error code such as EAGAIN , and it needs to be handled reasonably after judgment.

  • Memory management : Close the disconnected socket to prevent memory leakage.


5. Reference resources