← Back to PHP Course | Chapter 16: Testing & Tools | Lesson 6 of 10

PHP WebSockets

WebSockets browser और server के बीच एक खुली line रखते हैं, letters भेजने के बजाय एक phone call जैसा। दोनों sides कभी भी बात कर सकते हैं, जो chat और live updates के लिए बढ़िया है।

WebSockets का Introduction

WebSockets browser और server के बीच ज़रूरत भर एक single connection खुला रखते हैं, दोनों sides को कभी भी data push करने देते हुए -- HTTP के उलट, जहाँ server सिर्फ client के पूछने के बाद ही respond कर सकता है।

उदाहरण: Introduction to WebSockets

php
<?php
// Print "WebSockets keep one connection open so either side can push data anytime" to the output
echo "WebSockets keep one connection open so either side can push data anytime";
?>

Socket Server Initialization

stream_socket_server() एक raw socket खोलता है जो incoming connections सुनता है, वह low-level foundation बनाते हुए जिस पर एक PHP WebSocket server बना है।

उदाहरण: Socket Server Initialization

php
<?php
// Declare `$socket`, set to `stream_socket_server("tcp://127.0.0.1:0", $errno, $errstr)`
$socket = stream_socket_server("tcp://127.0.0.1:0", $errno, $errstr);
// Print `$socket ? "Socket server listening" : "Failed: $errstr"` to the output
echo $socket ? "Socket server listening" : "Failed: $errstr";
if ($socket) fclose($socket);
?>

Handshake Requests Handle करना

एक WebSocket connection establish करने के लिए एक specific handshake चाहिए: server client की Sec-WebSocket-Key लेता है, इसे एक fixed magic string के साथ combine करता है, इसे hash करता है, और upgrade confirm करने के लिए result return करता है।

उदाहरण: Handling Handshake Requests

php
<?php
// Declare `$key`, set to "dGhlIHNhbXBsZSBub25jZQ=="
$key = "dGhlIHNhbXBsZSBub25jZQ==";
// Declare `$magic`, set to "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
$magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
// Declare `$accept`, set to `base64_encode(sha1($key . $magic, true))`
$accept = base64_encode(sha1($key . $magic, true));
// Print `$accept` to the output
echo $accept;
?>

Data Frames Format करना

WebSocket messages plain text के बजाय binary-framed packets की तरह travel करते हैं, इसलिए outgoing strings को socket में लिखे जाने से पहले सही frame format में wrap करना ज़रूरी है।

उदाहरण: Formatting Data Frames

php
<?php
// Define the function `encodeFrame` taking `$message`
function encodeFrame($message) {
    // Declare `$length`, set to `strlen($message)`
    $length = strlen($message);
    // Return `chr(129) . chr($length) . $message` from this function
    return chr(129) . chr($length) . $message;
}
// Print `bin2hex(encodeFrame("hi"))` to the output
echo bin2hex(encodeFrame("hi"));
?>

Client Connection Manager

क्योंकि एक WebSocket server एक साथ कई clients serve कर सकता है, open connections को एक array registry में रखना आपको सबको broadcast करने, एक specific को message करने, या disconnect हो चुके connections साफ करने देता है।

उदाहरण: Client Connection Manager

php
<?php
// Declare `$clients` as an empty array
$clients = [];
// Set `$clients['conn1']` to "socket_resource_1"
$clients['conn1'] = "socket_resource_1";
// Set `$clients['conn2']` to "socket_resource_2"
$clients['conn2'] = "socket_resource_2";
// Loop over `$clients`, binding each item to `$id => $conn`
foreach ($clients as $id => $conn) {
    // Print "Broadcasting to $id\n" to the output
    echo "Broadcasting to $id\n";
}
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक normal web server request के तहत एक PHP WebSocket server चलाना, जबकि इसे एक long-running CLI process चाहिए।
  2. handshake header check skip करना, ताकि browsers connection accept न करें।
  3. WebSocket protocol में frames को सही से mask या unmask करना भूल जाना।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.