Current Location: Home> Latest Articles> Implementing the chat room application prototype based on socket_accept()

Implementing the chat room application prototype based on socket_accept()

M66 2025-06-05

In web programming, PHP is usually used to handle HTTP requests, but in fact PHP also provides a rich underlying network operation functions, including socket_* series functions, which can be used to implement TCP communication functions. This article will demonstrate how to build a simple chat room application prototype based on the PHP socket_accept() function to help you understand the socket programming mechanism of PHP.

1. Basic Principles

The basic mechanism of a chat room is: the server listens to a port, multiple clients connect to the server through socket, the server accepts the client's connection (via socket_accept() ), and broadcasts the received messages to all other clients.

2. Server code

The server is responsible for creating sockets, binding ports, listening for connections, and accepting client connections in a loop, and then processing and forwarding messages.

 <?php
$host = '0.0.0.0';
$port = 12345;
$clients = [];

$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, $host, $port);
socket_listen($server);

echo "Server started on $host:$port\n";

while (true) {
    $read = $clients;
    $read[] = $server;

    $write = $except = null;

    if (socket_select($read, $write, $except, null) < 1) {
        continue;
    }

    if (in_array($server, $read)) {
        $client = socket_accept($server);
        if ($client) {
            socket_getpeername($client, $addr, $port);
            echo "Client connected: {$addr}:{$port}\n";
            $clients[] = $client;
            socket_write($client, "Welcome to the chat room!\n");
        }
        unset($read[array_search($server, $read)]);
    }

    foreach ($read as $sock) {
        $data = @socket_read($sock, 2048, PHP_NORMAL_READ);
        if ($data === false) {
            $index = array_search($sock, $clients);
            socket_getpeername($sock, $addr, $port);
            echo "Client disconnected: {$addr}:{$port}\n";
            unset($clients[$index]);
            socket_close($sock);
            continue;
        }

        $data = trim($data);
        if (!empty($data)) {
            socket_getpeername($sock, $addr, $port);
            $message = "[{$addr}:{$port}] explain: {$data}\n";

            foreach ($clients as $client) {
                if ($client !== $sock) {
                    socket_write($client, $message);
                }
            }

            echo $message;
        }
    }
}

3. Client implementation method

Clients can use telnet or use browsers to connect with WebSocket proxy. However, if you want to use PHP to simulate a client to send messages, you can also use the following code:

 <?php
$host = '127.0.0.1';
$port = 12345;

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, $host, $port);

echo socket_read($socket, 2048);

while (true) {
    echo "Please enter a message: ";
    $msg = trim(fgets(STDIN));

    if ($msg === 'exit') {
        break;
    }

    socket_write($socket, $msg . "\n");

    $response = socket_read($socket, 2048);
    echo "Received a message: " . $response;
}

socket_close($socket);

4. Practical suggestions and extension ideas

  1. Multi-process support : You can use pcntl_fork() to achieve multi-process support to avoid blocking of the main process.

  2. Log management : Add a timestamp to each message to facilitate later troubleshooting.

  3. Identity : Setting a nickname or ID for each client can enhance the user experience.

  4. Front-end connection : You can integrate PHP chat rooms with web page front-end through WebSocket forwarding, and use middleware similar to http://m66.net/socket-proxy for communication bridge.

5. Summary

Through PHP Socket functions such as socket_accept() , we can implement a basic chat service in the command line environment. Although PHP is not the mainstream language for real-time communication, its underlying functions can still be used to complete the TCP communication function, which is suitable as an introductory example for learning network programming mechanisms. If you want to deploy it to a production environment, it is recommended to combine a more professional message queue and an asynchronous server framework to improve performance and stability.