Current Location: Home> Latest Articles> socket_accept() + socket_write(): Send a response to the client

socket_accept() + socket_write(): Send a response to the client

M66 2025-05-20

In PHP, socket programming is an underlying network communication method, suitable for building custom server programs. This article will introduce how to use the socket_accept() function to accept client connections and send a response to the client through the socket_write() function.

1. Create a socket and bind the port

First, we need to create a socket resource and bind it to the specified IP address and port to listen to client requests.

 <?php
// Create aTCP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    die("socket_create() fail: " . socket_strerror(socket_last_error()) . "\n");
}

// BindIPand ports,假设Bind本地IPand ports8080
$bind = socket_bind($socket, "0.0.0.0", 8080);
if ($bind === false) {
    die("socket_bind() fail: " . socket_strerror(socket_last_error($socket)) . "\n");
}

2. Listen and accept connections

After the binding is successful, we call socket_listen() to start listening, and then use socket_accept() to block and wait for the client to connect.

 // Start monitoring,The most allowed5Line up for connections
socket_listen($socket, 5);
echo "Server startup,Waiting for client connection...\n";

while (true) {
    // 阻塞Waiting for client connection
    $clientSocket = socket_accept($socket);
    if ($clientSocket === false) {
        echo "socket_accept() fail: " . socket_strerror(socket_last_error($socket)) . "\n";
        continue;
    }

    echo "Client is connected\n";

3. Read client request and send response

After receiving the client connection, the client data can be read through socket_read() and send a response to the client using socket_write() . For example, send a simple welcome message.

     // Read client data,Maximum read1024byte
    $input = socket_read($clientSocket, 1024);
    echo "Received a client message: $input\n";

    // Send response data
    $response = "Welcome to visitm66.netserver!\n";
    socket_write($clientSocket, $response, strlen($response));

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

4. Close the server socket

When the server needs to be shut down, call socket_close() to release the resource.

 socket_close($socket);

Summarize

The above code shows a simple PHP socket-based server example, with the focus on:

In this way, you can build a basic TCP server through PHP native socket programming, and flexibly handle client connections and communications.