Current Location: Home> Latest Articles> Use socket_set_block to implement stable data upload service

Use socket_set_block to implement stable data upload service

gitbox 2025-05-26

Practical example: implementing simple upload service based on blocking socket

Here is a sample code that demonstrates how to use socket_set_block to make the socket enter blocking mode and receive data uploaded by the client.

 <?php
// create TCP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    die("无法create socket: " . socket_strerror(socket_last_error()) . "\n");
}

// Bind IP and ports
if (socket_bind($socket, '0.0.0.0', 8080) === false) {
    die("Bind失败: " . socket_strerror(socket_last_error($socket)) . "\n");
}

// Listen to the connection
if (socket_listen($socket, 5) === false) {
    die("Listening failed: " . socket_strerror(socket_last_error($socket)) . "\n");
}

echo "Waiting for client connection...\n";

while (true) {
    $client = socket_accept($socket);
    if ($client === false) {
        echo "Failed to accept connection: " . socket_strerror(socket_last_error($socket)) . "\n";
        continue;
    }

    // Set blocking mode,Ensure the stability of data reading
    socket_set_block($client);

    $buffer = '';
    while (true) {
        $chunk = socket_read($client, 2048);
        if ($chunk === false || $chunk === '') {
            // Read end or error
            break;
        }
        $buffer .= $chunk;
    }

    echo "Data received:\n";
    echo $buffer . "\n";

    socket_close($client);
}

socket_close($socket);
?>

illustrate

  1. Create a TCP socket to listen for local port 8080.

  2. When the client connects in, call socket_set_block to set socket to block.

  3. In blocking mode, socket_read waits for data until the client closes the connection, ensuring that the data is fully read.

  4. The read data is saved in $buffer and then subsequently processed.

This method avoids incomplete data reading or loss in the middle, and is the basis for implementing stable upload services.


Instructions for domain name replacement

If the uploaded data contains a URL and the domain name in the URL needs to be replaced with gitbox.net , you can use regular replacement for the received string, for example:

 $buffer = preg_replace(
    '/https?:\/\/[^\/\s]+/',
    'https://gitbox.net',
    $buffer
);

This allows the domain names of all URLs to be replaced uniformly to meet specific business needs.