Home > Backend Development > PHP Tutorial > How to Build a WebSocket Server in PHP Using `socket_*` Functions?

How to Build a WebSocket Server in PHP Using `socket_*` Functions?

Susan Sarandon
Release: 2024-12-28 05:28:10
Original
292 people have browsed it

How to Build a WebSocket Server in PHP Using `socket_*` Functions?

How to Create a WebSocket Server in PHP

WebSocket is a technology that enables full-duplex communication between a web client and a web server. This allows for real-time data transfer, making it ideal for applications such as online gaming, instant messaging, and financial data streaming.

Outdated Code

The phpwebsockets library mentioned in the question is indeed outdated and does not support the latest WebSocket protocol. Additionally, updating it may not work as intended.

Creating a WebSocket Server

  1. Socket Creation: Create a master socket using the socket_create() function.
  2. Socket Binding: Bind the socket to a specific IP address and port using socket_bind().
  3. Socket Listening: Set the socket to listen for incoming connections using socket_listen().
  4. Accepting Connections: Use socket_accept() to accept incoming connections and create new client sockets.

Handshake Procedure

  1. Receiving Request: Receive the handshake request from the client using socket_recv().
  2. Parsing Headers: Parse the handshake request to obtain required headers such as Sec-WebSocket-Key.
  3. Generating Accept Key: Calculate the accept key based on the provided Sec-WebSocket-Key.
  4. Sending Response: Send the handshake response to the client, including the calculated accept key.

Processing Messages

  1. Receiving Data: Use socket_recv() to receive messages from clients.
  2. Decoding Data: Decode the received message if it's encoded using the WebSocket framing protocol.
  3. Processing Request: Handle the client's request and send an appropriate response.

Client-Server Interaction

  1. Client Connection: On the client side, use JavaScript's WebSocket object to establish a connection to the WebSocket server.
  2. Sending Data: Use send() to send data from the client to the server.
  3. Receiving Data: Set up event listeners for open, error, and message to handle messages received from the server.

Example Implementation

The following is an example PHP code snippet for a simple WebSocket server:

<?php
$master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($master, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($master, 'localhost', 12345);
socket_listen($master, 20);

$sockets = array($master);
$users = array();
$debug = false;

while (true) {
    $changed = $sockets;
    socket_select($changed, $write = NULL, $except = NULL, NULL);

    foreach ($changed as $socket) {
        if ($socket == $master) {
            $client = socket_accept($master);
            if ($client < 0) {
                console("socket_accept() failed");
                continue;
            } else {
                connect($client);
            }
        } else {
            $bytes = @socket_recv($socket, $buffer, 2048, 0);
            if ($bytes == 0) {
                disconnect($socket);
            } else {
                $user = getuserbysocket($socket);
                if (!$user->handshake) {
                    dohandshake($user, $buffer);
                } else {
                    process($user, $buffer);
                }
            }
        }
    }
}
Copy after login

This code skeleton demonstrates the steps discussed above, including creating and listening on the master socket, accepting incoming connections, performing the WebSocket handshake, and processing client messages. The complete script should be supplemented with the remaining functions described earlier, such as connect(), disconnect(), and process().

The above is the detailed content of How to Build a WebSocket Server in PHP Using `socket_*` Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template