Current Location: Home> Latest Articles> Communication with front-end WebSocket client: Implementation idea of ​​socket_accept

Communication with front-end WebSocket client: Implementation idea of ​​socket_accept

M66 2025-05-20

In Web applications, WebSocket provides a way to establish a full duplex communication channel between the client and the server. Compared with traditional HTTP requests, WebSocket allows the server to actively push messages to the client. Although PHP is not the most suitable language for long connections in the traditional sense, it can still implement simple WebSocket services through underlying socket programming. This article will introduce how to use PHP's socket_accept function to achieve communication with the front-end WebSocket client.

Prerequisites

In order to use PHP's socket functionality, you need to make sure that the sockets extension is enabled in PHP. It can be enabled in php.ini :

 extension=sockets

Then restart your PHP service.

Create a WebSocket Server

The handshake process of WebSocket follows certain protocol specifications. We need to perform an HTTP protocol-level handshake confirmation after receiving the client request before we can perform WebSocket data frame communication.

Here is a complete PHP script example:

 <?php
$host = '0.0.0.0';
$port = 8080;

$serverSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($serverSocket, $host, $port);
socket_listen($serverSocket);

echo "WebSocket The server starts at $host:$port\n";

while (true) {
    $clientSocket = socket_accept($serverSocket);
    if ($clientSocket === false) {
        continue;
    }

    // Read client request header
    $request = socket_read($clientSocket, 1024);
    if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $request, $matches)) {
        $key = trim($matches[1]);
        $acceptKey = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
        $headers = "HTTP/1.1 101 Switching Protocols\r\n";
        $headers .= "Upgrade: websocket\r\n";
        $headers .= "Connection: Upgrade\r\n";
        $headers .= "Sec-WebSocket-Accept: $acceptKey\r\n\r\n";
        socket_write($clientSocket, $headers);
        echo "WebSocket Handshake is completed。\n";
    }

    // Simple read and send WebSocket information
    while (true) {
        $data = socket_read($clientSocket, 2048);
        if ($data === false) {
            break;
        }

        $decoded = unmask($data);
        echo "接收到客户端information: $decoded\n";

        $response = mask("What you sent is: $decoded");
        socket_write($clientSocket, $response);
    }

    socket_close($clientSocket);
}

socket_close($serverSocket);

// Analysis WebSocket frame
function unmask($payload) {
    $length = ord($payload[1]) & 127;
    if ($length == 126) {
        $masks = substr($payload, 4, 4);
        $data = substr($payload, 8);
    } elseif ($length == 127) {
        $masks = substr($payload, 10, 4);
        $data = substr($payload, 14);
    } else {
        $masks = substr($payload, 2, 4);
        $data = substr($payload, 6);
    }

    $text = '';
    for ($i = 0; $i < strlen($data); ++$i) {
        $text .= $data[$i] ^ $masks[$i % 4];
    }
    return $text;
}

// structure WebSocket 数据frame
function mask($text) {
    $b1 = 0x81; // FIN=1, opcode=0x1 (text)
    $length = strlen($text);

    if ($length <= 125) {
        $header = pack('CC', $b1, $length);
    } elseif ($length <= 65535) {
        $header = pack('CCn', $b1, 126, $length);
    } else {
        $header = pack('CCNN', $b1, 127, 0, $length);
    }

    return $header . $text;
}
?>

Front-end client example

On the front end, you can communicate with the PHP WebSocket service in the following ways:

 <script>
    const socket = new WebSocket("ws://m66.net:8080");

    socket.onopen = () => {
        console.log("The connection has been established");
        socket.send("Hello PHP WebSocket!");
    };

    socket.onmessage = (event) => {
        console.log("收到information:", event.data);
    };

    socket.onclose = () => {
        console.log("The connection is closed");
    };
</script>

Note: ws://m66.net:8080 here is the address of your server. Please set the domain name and port mapping according to the deployment environment.

Summarize

By using PHP's socket_accept and related functions, we can implement a basic WebSocket server logic. This method is suitable for learning and experimental purposes. For production environments, it is recommended to use higher performance solutions such as Ratchet, Swoole or use a dedicated WebSocket server (such as Node.js, Go).

Although PHP is not designed for long connections, its underlying socket is powerful and can meet basic bidirectional communication needs. Through the examples in this article, you can build a simple PHP WebSocket server to interact with the front-end client.