### Echo Logger Setup (PHP) Source: https://github.com/textalk/websocket-php/blob/master/docs/Examples.md This snippet demonstrates how to initialize an EchoLogger for debugging purposes within the WebSocket library. It shows how to set the logger for both client and server instances. This logger is suitable for development environments and prints synchronous information. ```php namespace WebSocket; $logger = new EchoLogger(); $client = new Client('ws://echo.websocket.org/'); $client->setLogger($logger); $server = new Server(); $server->setLogger($logger); ``` -------------------------------- ### Send Client Usage (PHP) Source: https://github.com/textalk/websocket-php/blob/master/docs/Examples.md This example showcases a basic client that sends a single message and waits for a response. It supports sending text or ping messages and can connect to a specified URI. The `--debug` flag enables runtime debugging. ```bash php examples/send.php --opcode text "A text message" php examples/send.php --opcode ping "ping it" php examples/send.php --uri ws://echo.websocket.org "A text message" php examples/send.php --opcode text --debug "A text message" ``` -------------------------------- ### Install Websocket PHP Library with Composer Source: https://github.com/textalk/websocket-php/blob/master/README.md This command installs the Textalk/websocket-php library using Composer, the dependency manager for PHP. It specifies the preferred way to add the library to a PHP project and lists version compatibility notes for different PHP versions. ```bash composer require textalk/websocket ``` -------------------------------- ### Random Server Example (PHP) Source: https://github.com/textalk/websocket-php/blob/master/docs/Examples.md This server continuously sends and receives random messages, utilizing random WebSocket options. It can be configured to listen on a specific port and allows setting timeout and fragment size. Runtime debugging is supported through the `--debug` flag. ```bash php examples/random_server.php --port 8080 php examples/random_server.php --timeout 5 --fragment_size 16 php examples/random_server.php --debug ``` -------------------------------- ### WebSocket Client Constructor Options Example Source: https://github.com/textalk/websocket-php/blob/master/docs/Client.md This example showcases how to utilize the various constructor options for the WebSocket client, including setting a stream context with SSL verification disabled, defining message filters, fragment size, custom headers, a PSR-3 logger, and connection timeout. ```php $context = stream_context_create(); stream_context_set_option($context, 'ssl', 'verify_peer', false); stream_context_set_option($context, 'ssl', 'verify_peer_name', false); $client = new WebSocket\Client("ws://echo.websocket.org/", [ 'context' => $context, // Attach stream context created above 'filter' => ['text', 'binary', 'ping'], // Specify message types for receive() to return 'headers' => [ // Additional headers, used to specify subprotocol 'Sec-WebSocket-Protocol' => 'soap', 'origin' => 'localhost', ], 'logger' => $my_psr3_logger, // Attach a PSR3 compatible logger 'return_obj' => true, // Return Message instance rather than just text 'timeout' => 60, // 1 minute time out ]); ``` -------------------------------- ### Install and Update Dependencies with Composer Source: https://github.com/textalk/websocket-php/blob/master/docs/Contributing.md This snippet shows how to manage project dependencies using Composer, a popular dependency manager for PHP. It covers both installing new dependencies and updating existing ones. ```makefile # Install dependencies make install ``` ```makefile # Update dependencies make update ``` -------------------------------- ### Echo Server Implementation (PHP) Source: https://github.com/textalk/websocket-php/blob/master/docs/Examples.md A simple WebSocket server that echoes back received messages. It can be configured to listen on a specific port and supports runtime debugging. Certain commands like 'auth', 'close', 'exit', 'headers', 'ping', 'pong', and 'stop' trigger specific server actions. ```bash php examples/echoserver.php php examples/echoserver.php --port 8080 php examples/echoserver.php --debug ``` -------------------------------- ### Random Client Example (PHP) Source: https://github.com/textalk/websocket-php/blob/master/docs/Examples.md This client continuously sends and receives random messages using varied WebSocket options. It allows specifying the connection URI, timeout, and fragment size. Runtime debugging is also available via the `--debug` flag. ```bash php examples/random_client.php --uri ws://echo.websocket.org php examples/random_client.php --timeout 5 --fragment_size 16 php examples/random_client.php --debug ``` -------------------------------- ### PHP WebSocket Server: Sending Various Message Types Source: https://github.com/textalk/websocket-php/blob/master/docs/Server.md Provides examples of sending different types of WebSocket messages using convenience methods and the generic send method. It covers sending text, binary data, ping frames, and pong frames, illustrating how to specify the opcode and whether the message should be masked. ```php $server = new WebSocket\Server(); // Convenience methods $server->text('A plain text message'); // Send an opcode=text message $server->binary($binary_string); // Send an opcode=binary message $server->ping(); // Send an opcode=ping frame $server->pong(); // Send an unsolicited opcode=pong frame // Generic send method $server->send($payload); // Sent as masked opcode=text $server->send($payload, 'binary'); // Sent as masked opcode=binary $server->send($payload, 'binary', false); // Sent as unmasked opcode=binary ``` -------------------------------- ### PHP Example: Receiving and Inspecting WebSocket Message Object Source: https://github.com/textalk/websocket-php/blob/master/docs/Message.md Example demonstrating how to send a text message using a WebSocket client configured to return message objects. It then receives the message, accesses its properties like opcode, length, content, and timestamp, and finally closes the connection. ```php $client = new WebSocket\Client('ws://echo.websocket.org/', ['return_obj' => true]); $client->text('Hello WebSocket.org!'); // Echo return same message as sent $message = $client->receive(); echo $message->getOpcode(); // -> "text" echo $message->getLength(); // -> 20 echo $message->getContent(); // -> "Hello WebSocket.org!" echo $message->hasContent(); // -> true echo $message->getTimestamp()->format('H:i:s'); // -> 19:37:18 $client->close(); ``` -------------------------------- ### Filtering WebSocket Received Messages Source: https://github.com/textalk/websocket-php/blob/master/docs/Client.md This example illustrates how to filter the types of messages received by the `receive()` method. By setting the 'filter' option in the client's constructor, you can specify whether to receive only 'text', 'binary', or a combination of message opcodes. ```php $client = new WebSocket\Client("ws://echo.websocket.org/", ['filter' => ['text']]); $client->receive(); // Only return 'text' messages $client = new WebSocket\Client("ws://echo.websocket.org/", ['filter' => ['text', 'binary', 'ping', 'pong', 'close']]); $client->receive(); // Return all messages ``` -------------------------------- ### PHP WebSocket Server: Filtering Received Messages Source: https://github.com/textalk/websocket-php/blob/master/docs/Server.md Shows how to filter the types of messages the server will process using the 'filter' option in the constructor. Examples demonstrate receiving only 'text' messages or a broader set including 'text', 'binary', 'ping', 'pong', and 'close' frames. This allows for selective handling of client communications. ```php $server = new WebSocket\Server(['filter' => ['text']]); $server->receive(); // only return 'text' messages $server = new WebSocket\Server(['filter' => ['text', 'binary', 'ping', 'pong', 'close']]); $server->receive(); // return all messages ``` -------------------------------- ### PHP WebSocket Server: Constructor Options Configuration Source: https://github.com/textalk/websocket-php/blob/master/docs/Server.md Demonstrates how to configure the WebSocket server using an associative array of options passed to the constructor. This includes setting message filters, fragment size, attaching a PSR-3 logger, specifying the listening port, enabling object return for messages, and setting connection timeouts. ```php $server = new WebSocket\Server([ 'filter' => ['text', 'binary', 'ping'], // Specify message types for receive() to return 'logger' => $my_psr3_logger, // Attach a PSR3 compatible logger 'port' => 9000, // Listening port 'return_obj' => true, // Return Message instance rather than just text 'timeout' => 60, // 1 minute time out ]); ``` -------------------------------- ### Run All Tests using Makefile Source: https://github.com/textalk/websocket-php/blob/master/tests/README.md This command executes all unit tests for the project using a Makefile. It's a simple way to ensure the codebase is functioning correctly. ```shell make test ``` -------------------------------- ### Run Unit Tests and Create Coverage Reports Source: https://github.com/textalk/websocket-php/blob/master/docs/Contributing.md These commands are used for running unit tests and generating code coverage reports using PHPUnit. Maintaining 100% code coverage is a strict requirement for all contributions. ```makefile # Run unit tests make test ``` ```makefile # Create coverage make coverage ``` -------------------------------- ### WebSocket Client Class Synopsis Source: https://github.com/textalk/websocket-php/blob/master/docs/Client.md This code snippet provides a full synopsis of the WebSocket client class, outlining its constructor, methods for sending and receiving messages, and properties for managing connection status and configuration. It serves as a reference for available client functionalities. ```php WebSocket\Client { public __construct(UriInterface|string $uri, array $options = []); public __destruct(); public __toString() : string; public text(string $payload) : void; public binary(string $payload) : void; public ping(string $payload = '') : void; public pong(string $payload = '') : void; public send(Message|string $payload, string $opcode = 'text', bool $masked = true) : void; public close(int $status = 1000, mixed $message = 'ttfn') : void; public receive() : Message|string|null; public getName() : string|null; public getRemoteName() : string|null; public getLastOpcode() : string; public getCloseStatus() : int; public isConnected() : bool; public setTimeout(int $seconds) : void; public setFragmentSize(int $fragment_size) : self; public getFragmentSize() : int; public setLogger(Psr\Log\LoggerInterface $logger = null) : void; } ``` -------------------------------- ### WebSocket Server API Source: https://github.com/textalk/websocket-php/blob/master/docs/Server.md Details the WebSocket Server class, including its constructor, methods for handling connections and messages, and retrieving server information. ```APIDOC ## WebSocket\Server Class API ### Description This class provides a basic implementation for a single-stream, single-thread WebSocket server. It handles the WebSocket upgrade handshake, implicit close, and ping/pong operations internally. It does not support threading or automatic association of continuous client requests. ### Methods #### Constructor - `__construct(array $options = [])`: Initializes the WebSocket server with optional configuration settings. #### Connection Handling - `accept() : bool`: Accepts a new client connection. Returns `true` on success, `false` otherwise. - `close(int $status = 1000, mixed $message = 'ttfn') : void`: Closes the WebSocket connection with the specified status code and message. - `isConnected() : bool`: Checks if the WebSocket connection is currently active. - `setTimeout(int $seconds) : void`: Sets the socket timeout in seconds. #### Message Handling - `text(string $payload) : void`: Sends a text message to the client. - `binary(string $payload) : void`: Sends a binary message to the client. - `ping(string $payload = '') : void`: Sends a ping frame to the client. - `pong(string $payload = '') : void`: Sends a pong frame to the client. - `send(Message|string $payload, string $opcode = 'text', bool $masked = true) : void`: Sends a generic message with a specified opcode and masking option. - `receive() : Message|string|null`: Receives a message from the client. Returns a `Message` object or string, or `null` if no message is received or an error occurs. #### Information Retrieval - `getPort() : int`: Gets the server's listening port. - `getPath() : string`: Gets the server's request path. - `getRequest() : array`: Gets the raw request details. - `getHeader(string $header_name) : string|null`: Gets a specific header from the request. - `getName() : string|null`: Gets the server name. - `getRemoteName() : string|null`: Gets the remote client's name (IP address and port). - `getLastOpcode() : string`: Gets the opcode of the last received message. - `getCloseStatus() : int`: Gets the close status code of the last received close frame. - `getFragmentSize() : int`: Gets the current fragment size setting. #### Configuration - `setFragmentSize(int $fragment_size) : self`: Sets the maximum fragment size for sending messages. - `setLogger(Psr\Log\LoggerInterface $logger = null) : void`: Sets a PSR-3 compatible logger for the server. ### Constructor Options The `$options` parameter in the constructor accepts an associative array: - `filter` (array): Array of opcodes to return on `receive()`. Default `['text', 'binary']`. - `fragment_size` (int): Maximum payload size. Default 4096. - `logger` (Psr\Log\LoggerInterface): A PSR-3 compatible logger instance. - `port` (int): The server port to listen to. Default 8000. - `return_obj` (bool): If `true`, `receive()` returns a `Message` object. Default `false`. - `timeout` (int): Socket timeout in seconds. Default 5. #### Example Constructor Usage ```php $server = new WebSocket\Server([ 'filter' => ['text', 'binary', 'ping'], 'logger' => $my_psr3_logger, 'port' => 9000, 'return_obj' => true, 'timeout' => 60, ]); ``` ### Exceptions - `WebSocket\BadOpcodeException`: Thrown if an invalid opcode is provided. - `WebSocket\ConnectionException`: Thrown on any socket I/O failure. - `WebSocket\TimeoutException`: Thrown when the socket experiences a timeout. ``` -------------------------------- ### Simple Receive-Send Operation Source: https://github.com/textalk/websocket-php/blob/master/docs/Server.md Demonstrates a basic WebSocket server interaction where it accepts a connection, receives a message, sends the same message back, and then closes the connection. ```APIDOC ## Simple Receive-Send Operation ### Description This example illustrates a minimal WebSocket server setup. It listens for a single client message, echoes it back, and terminates the connection. ### Method `WebSocket\Server` ### Endpoint N/A (Server-side implementation) ### Request Example ```php $server = new WebSocket\Server(); $server->accept(); $message = $server->receive(); $server->text($message); $server->close(); ``` ### Response Example (The server echoes the received message back to the client.) ``` -------------------------------- ### Listening to Clients Continuously Source: https://github.com/textalk/websocket-php/blob/master/docs/Server.md Shows how to keep the WebSocket server running to continuously listen for incoming messages within a loop, with error handling for connection issues. ```APIDOC ## Listening to Clients Continuously ### Description This example demonstrates how to maintain an active WebSocket server that perpetually listens for incoming client messages. It utilizes a `while` loop and exception handling to manage connection stability and potential errors. ### Method `WebSocket\Server` ### Endpoint N/A (Server-side implementation) ### Request Example ```php $server = new WebSocket\Server(); while ($server->accept()) { try { $message = $server->receive(); // Act on received message // Break while loop to stop listening } catch (\WebSocket\ConnectionException $e) { // Possibly log errors // The loop will attempt to re-connect on the next iteration } } $server->close(); ``` ### Response Example (The server processes messages received within the loop. The loop terminates when `accept()` returns `false` or if an explicit `break` is encountered.) ``` -------------------------------- ### Convenience Methods for Sending WebSocket Messages Source: https://github.com/textalk/websocket-php/blob/master/docs/Client.md This code demonstrates the convenience methods provided by the WebSocket client for sending messages with specific opcodes: `text()`, `binary()`, `ping()`, and `pong()`. It also shows the generic `send()` method for more control. ```php $client = new WebSocket\Client("ws://echo.websocket.org/"); // Convenience methods $client->text('A plain text message'); // Send an opcode=text message $client->binary($binary_string); // Send an opcode=binary message $client->ping(); // Send an opcode=ping frame $client->pong(); // Send an unsolicited opcode=pong frame // Generic send method $client->send($payload); // Sent as masked opcode=text $client->send($payload, 'binary'); // Sent as masked opcode=binary $client->send($payload, 'binary', false); // Sent as unmasked opcode=binary ``` -------------------------------- ### Basic WebSocket Client Connection and Message Exchange in PHP Source: https://github.com/textalk/websocket-php/blob/master/README.md This PHP code snippet demonstrates how to establish a connection to a WebSocket server, send a text message, receive a response, and then close the connection using the WebSocket client. It requires the WebSocket client class to be available. ```php $client = new WebSocket\Client("ws://echo.websocket.org/"); $client->text("Hello WebSocket.org!"); echo $client->receive(); $client->close(); ``` -------------------------------- ### PHP WebSocket Message Factory Class Synopsis Source: https://github.com/textalk/websocket-php/blob/master/docs/Message.md Synopsis of the WebSocket\Message\Factory class, which is responsible for creating Message instances. It has a single public method `create` that takes an opcode and payload to instantiate the appropriate message object. ```php WebSocket\Message\Factory { public create(string $opcode, string $payload = '') : Message; } ``` -------------------------------- ### PHP WebSocket Server: Continuous Client Listening Source: https://github.com/textalk/websocket-php/blob/master/docs/Server.md Illustrates how to continuously listen for incoming messages from clients by placing the receive operation within a while loop. It includes basic exception handling for connection failures, allowing the server to attempt reconnection in the next iteration. This pattern is essential for maintaining active client connections. ```php $server = new WebSocket\Server(); while ($server->accept()) { try { $message = $server->receive(); // Act on received message // Break while loop to stop listening } catch (\WebSocket\ConnectionException $e) { // Possibly log errors } } $server->close(); ``` -------------------------------- ### Sending Messages Source: https://github.com/textalk/websocket-php/blob/master/docs/Server.md Illustrates the various methods available for sending different types of messages (text, binary, ping, pong) to connected WebSocket clients. ```APIDOC ## Sending Messages ### Description This guide covers the different ways to send data to WebSocket clients using the `WebSocket\Server` class, including convenience methods for common message types and a generic `send` method. ### Method `WebSocket\Server` ### Endpoint N/A (Server-side implementation) ### Request Example ```php $server = new WebSocket\Server(); // Convenience methods for specific opcodes: $server->text('A plain text message'); // Sends an opcode=text message $server->binary($binary_string); // Sends an opcode=binary message $server->ping(); // Sends an opcode=ping frame $server->pong(); // Sends an unsolicited opcode=pong frame // Generic send method for flexible message sending: $server->send($payload); // Sends as masked opcode=text $server->send($payload, 'binary'); // Sends as masked opcode=binary $server->send($payload, 'binary', false); // Sends as unmasked opcode=binary ``` ### Response Example (These methods send data to the connected client. The success of the send operation depends on the client's connection status.) ``` -------------------------------- ### PHP WebSocket Message Abstract Class Synopsis Source: https://github.com/textalk/websocket-php/blob/master/docs/Message.md Synopsis of the abstract WebSocket\Message\Message class, detailing its constructor and methods for retrieving opcode, length, timestamp, content, and setting content. It serves as the base for all message types. ```php WebSocket\Message\Message { public __construct(string $payload = ''); public __toString() : string; public getOpcode() : string; public getLength() : int; public getTimestamp() : DateTime; public getContent() : string; public setContent(string $payload = '') : void; public hasContent() : bool; } ``` -------------------------------- ### Continuous WebSocket Message Listening Source: https://github.com/textalk/websocket-php/blob/master/docs/Client.md This snippet shows how to continuously listen for incoming messages from a WebSocket server by using a `while` loop around the `receive()` method. It includes a `try-catch` block to handle `ConnectionException`, allowing for automatic re-connection attempts. ```php $client = new WebSocket\Client("ws://echo.websocket.org/"); while (true) { try { $message = $client->receive(); // Act on received message // Break while loop to stop listening } catch (\WebSocket\ConnectionException $e) { // Possibly log errors } } $client->close(); ``` -------------------------------- ### Basic WebSocket Server Message Handling in PHP Source: https://github.com/textalk/websocket-php/blob/master/README.md This PHP code demonstrates a rudimentary single-threaded WebSocket server. It accepts a client connection, receives a message from the client, sends the same message back to the client, and then closes the connection. This implementation does not support threading or automatic handling of continuous client requests. ```php $server = new WebSocket\Server(); $server->accept(); $message = $server->receive(); $server->text($message); $server->close(); ``` -------------------------------- ### Check Code Standard Adherence Source: https://github.com/textalk/websocket-php/blob/master/docs/Contributing.md This command checks if the project's code adheres to the specified PSR-1 and PSR-12 coding standards. It's a crucial step to ensure code quality and consistency across the project. ```makefile # Check code standard adherence make cs-check ``` -------------------------------- ### Filtering Received Messages Source: https://github.com/textalk/websocket-php/blob/master/docs/Server.md Explains how to configure the server to only receive specific types of WebSocket messages (opcodes) using the 'filter' option. ```APIDOC ## Filtering Received Messages ### Description This section details how to control which types of WebSocket messages the server processes using the `filter` option in the constructor. By default, only 'text' and 'binary' messages are returned by `receive()`. ### Method `WebSocket\Server` ### Endpoint N/A (Server-side configuration) ### Parameters #### Constructor Options - `filter` (array): An array of opcodes (e.g., 'text', 'binary', 'ping', 'pong', 'close') to specify which message types `receive()` should return. ### Request Example ```php // Only return 'text' messages $server = new WebSocket\Server(['filter' => ['text']]); $server->receive(); // Return all message types $server = new WebSocket\Server(['filter' => ['text', 'binary', 'ping', 'pong', 'close']]); $server->receive(); ``` ### Response Example (The `receive()` method will only return messages corresponding to the opcodes specified in the `filter` array.) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.