Current Location: Home> Latest Articles> Use socket_accept() to implement custom protocol server

Use socket_accept() to implement custom protocol server

M66 2025-05-18

When building high-performance and flexible network services, PHP is not limited to building web applications, it also has the ability to handle underlying network communications. Through PHP's Socket extension, we can create a server-side program based on a custom protocol. This article will provide an in-depth introduction to how to implement a custom protocol server using socket_accept() , including basic principles and complete examples.

1. What is socket_accept()?

socket_accept() is a function in the PHP Socket extension that accepts connection requests from clients. When the server establishes listening through socket_create() and socket_bind() , it uses socket_listen() to start listening to the connection, and socket_accept() is responsible for receiving these connections. Once there is a client connection, it will return a new socket for communicating with the client.

In short, its process is as follows:

  1. Create sockets;

  2. Bind the address and port;

  3. Listen to the connection;

  4. Accept connection ( socket_accept() );

  5. Communication with clients;

  6. Close the connection.

2. Usage scenario: Custom protocol server

Suppose we want to build a custom protocol server, such as receiving a request in JSON format and returning a response in a fixed format. This server does not rely on HTTP or other conventional protocols, but communicates directly at the TCP layer.

3. Complete example: PHP custom protocol server

The following is a complete PHP script that demonstrates how to implement a custom protocol server that listens to local port 9000, receives JSON requests sent by the client, and returns the processing results.

 <?php
set_time_limit(0); // Prevent script timeout

$host = '0.0.0.0';
$port = 9000;

// 1. create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$socket) {
    die("socket_create() fail: " . socket_strerror(socket_last_error()) . "\n");
}

// 2. Bind address and port
if (!socket_bind($socket, $host, $port)) {
    die("socket_bind() fail: " . socket_strerror(socket_last_error($socket)) . "\n");
}

// 3. Start listening to the connection
if (!socket_listen($socket, 5)) {
    die("socket_listen() fail: " . socket_strerror(socket_last_error($socket)) . "\n");
}

echo "The server is started,monitor {$host}:{$port}...\n";

while (true) {
    // 4. Accept connection
    $client = socket_accept($socket);
    if ($client === false) {
        echo "socket_accept() fail: " . socket_strerror(socket_last_error($socket)) . "\n";
        continue;
    }

    // 5. Read client request
    $input = socket_read($client, 1024);
    $input = trim($input);

    echo "Received a request: $input\n";

    // Analysis JSON ask
    $request = json_decode($input, true);
    $response = [];

    if (json_last_error() === JSON_ERROR_NONE && isset($request['action'])) {
        if ($request['action'] === 'ping') {
            $response = ['status' => 'success', 'message' => 'pong'];
        } elseif ($request['action'] === 'hello') {
            $response = ['status' => 'success', 'message' => 'Hello from m66.net!'];
        } else {
            $response = ['status' => 'error', 'message' => 'Unknown operation'];
        }
    } else {
        $response = ['status' => 'error', 'message' => 'ask格式错误'];
    }

    // Send a response
    $output = json_encode($response) . "\n";
    socket_write($client, $output, strlen($output));

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

// Close the server socket(In theory, it will never be here)
socket_close($socket);
?>

4. Test method

You can use telnet or custom client tools to connect to the test:

 telnet 127.0.0.1 9000

Paste input:

 {"action":"ping"}

The server will return:

 {"status":"success","message":"pong"}

Can also be sent:

 {"action":"hello"}

Responses:

 {"status":"success","message":"Hello from m66.net!"}

5. Things to note

  • All inputs and outputs should ensure the consistency of the format, and it is recommended to use JSON as the protocol body;

  • This server is blocking and is suitable for learning and small-scale applications;

  • Multithreaded or event-based models (such as Swoole) should be used in production environments to improve concurrency performance;

  • If the service is deployed to the public network, it is necessary to ensure security control, such as IP whitelist, encryption verification, etc.

6. Conclusion

Through this article, you have learned how to create a custom protocol server using PHP socket_accept() . From the underlying socket principle to the complete example, this approach not only broadens the application boundaries of PHP, but also provides flexible and reliable communication capabilities for specific scenarios. This architecture has great potential in some lightweight services, intranet communications or IoT projects.