Download the PHP package mita/uranus-socket-server without Composer
On this page you can find all versions of the php package mita/uranus-socket-server. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download mita/uranus-socket-server
More information about mita/uranus-socket-server
Files in mita/uranus-socket-server
Package uranus-socket-server
Short Description A PHP Socket Server Library using Ratchet
License MIT
Informations about the package uranus-socket-server
Here is a revised and more structured version of the UranusSocketServer documentation, now including additional sections on configuring routes, creating controllers, and understanding packet structure after the connection is established:
UranusSocketServer
UranusSocketServer is a powerful, scalable, and easy-to-use PHP library designed for building high-performance WebSocket applications. With features like a flexible middleware pipeline, comprehensive event management, and efficient connection handling, UranusSocketServer empowers developers to create sophisticated WebSocket solutions effortlessly.
Features
- Modular Architecture: Easily extend and customize your WebSocket server.
- Dependency Injection: Fully DI-compliant for clean and maintainable code.
- Scalability: Efficiently handles numerous simultaneous WebSocket connections.
- Customizable Routing: Route messages to controllers with support for middleware.
- Event-Driven: Hook into key lifecycle events for enhanced control.
Quick Start Guide
1. Installation
Install the library using Composer:
2. Configuration
2.1 Setting Up Routes
Create a routes.yaml
file to define your WebSocket routes:
2.2 Creating a Controller
Create a controller to handle incoming WebSocket messages:
2.3 Understanding Packet Structure
When sending data to the server, the packet should be structured as a JSON object with at least two keys: route
and msg
.
- route: Specifies the WebSocket route that the packet should be sent to.
- msg: Contains the message or data you wish to send.
Example Packet:
3. Running the Basic Chat Application Example
This section demonstrates how to quickly set up a simple WebSocket chat server.
3.1 Clone the Repository
3.2 Install Dependencies
3.3 Navigate to the Example Directory
3.4 Introduction to index.php
The index.php
file is the entry point for the WebSocket server. It initializes the server with basic settings:
3.5 Run the WebSocket Server
Start the WebSocket server with:
3.6 Connect to the Server
Use a WebSocket client to connect to ws://127.0.0.1:7654
and send JSON packets like:
Join a Room:
Send a Message to the Room:
4. Running the ChatWithAuth Application Example
This example builds on the basic chat functionality by adding token-based authentication.
4.1 Clone the Repository
4.2 Install Dependencies
4.3 Navigate to the Example Directory
Navigate to the ChatWithAuth
example directory:
4.4 Introduction to index.php
In this example, the index.php
file registers an AuthPlugin
for token-based authentication:
This example demonstrates how to create and integrate a custom plugin. By following this pattern, you can develop and register your plugins to extend the server’s capabilities.
4.5 Update the Secret Key
Replace 'your_secret_key'
with your desired secret key for authentication.
4.6 Run the WebSocket Server
Start the WebSocket server:
4.7 Connect to the Server
Use a WebSocket client to connect to ws://127.0.0.1:7654
, including the access_token
in the URI query string.
Example Connection URI:
4.8 Join a Room
Authenticate and join a chat room with the following JSON payload:
4.9 Send a Message to the Room
Once authenticated and joined, send a message to the room:
4.10 Explanation of AuthPlugin.php
The AuthPlugin.php
file is a custom plugin that adds token-based authentication to your WebSocket server. Below is a detailed explanation of its key parts:
Explanation: The constructor initializes the plugin with a secret key and a token parameter name. This setup allows you to easily configure which token to validate and how to validate it.
Explanation: The register
method hooks the plugin into the WebSocket server by listening for specific events like middleware.register
and connection.open
. This is where the authentication logic gets integrated into the server's lifecycle.
Explanation: The onRegisterMiddleware
method adds the authentication middleware to the pipeline. This ensures that each message passing through the server is checked for authentication.
Explanation: The onOpen
method is invoked when a new WebSocket connection is opened. It extracts the token from the connection URI and validates it. If the token is invalid, the connection is closed immediately.
Explanation: The handle
method processes incoming WebSocket messages. It checks the token within the message metadata, ensuring that only authenticated users can interact with the server.
Explanation: The validateToken
method is a utility function that compares the provided token with the secret key. This simple method can be expanded for more complex validation logic if needed.
Code Overview for ChatWithAuth Example
ChatController.php
: Handles room join and message publishing logic.AuthPlugin.php
: Middleware for token-based authentication.ChatService.php
: Manages room subscriptions and broadcasts messages.index.php
: Entry point, initializes the WebSocket server and registers theAuthPlugin
.routes.yaml
: Defines the routes for joining and messaging within rooms.
API Documentation
1. SocketServer
The SocketServer
class is the entry point for your WebSocket server.
-
run()
Starts the WebSocket server.
-
registerEventListener(string $eventName, callable $listener)
Registers an event listener.
2. RoutingMiddleware
The RoutingMiddleware
class handles routing of incoming WebSocket messages.
-
handle(ConnectionInterface $conn, PacketInterface $packet, callable $next)
Routes the message to the appropriate controller.
3. MiddlewarePipeline
Processes messages through a series of middleware.
-
add(MiddlewareInterface $middleware)
Adds a middleware to the pipeline.
-
process(ConnectionInterface $conn, PacketInterface $packet, callable $finalHandler)
Processes the packet through the middleware pipeline.
4. ConnectionManager
Manages WebSocket connections and their subscriptions.
-
add(ConnectionInterface $conn)
Adds a new connection.
-
remove(ConnectionInterface $conn)
Removes a connection.
5. EventDispatcher
Manages event listeners and dispatching events.
-
addListener(string $eventName, callable $listener)
Registers an event listener.
-
dispatch(string $eventName, $eventData = null)
Dispatches an event to registered listeners.
6. Packet
Represents a WebSocket message packet.
-
getRoute()
Returns the route of the packet.
-
getMessage()
Returns the message content.
-
getMetadata(string $key = null)
Returns metadata or specific key value.
7. PacketFactory
Creates Packet
instances from JSON strings.
-
createFromJson(string $json): PacketInterface
Creates a
Packet
from a JSON string.
8. PluginManager
Manages the lifecycle of plugins in the system.
-
addPlugin(PluginInterface $plugin)
Adds a plugin to the manager.
-
registerPlugins(EventDispatcherInterface $dispatcher)
Registers all plugins with the event dispatcher and dispatches
plugin.registered
event. -
bootPlugins()
Boots all registered plugins.
Creating a Plugin
To create a plugin in UranusSocketServer, you need to implement the PluginInterface
. A plugin can be used to add custom functionality to the server, such as authentication, logging, or other middleware. Here's a basic outline of how to create and register a plugin:
-
Implement the
PluginInterface
: - Add the Plugin to the Server:
By following this pattern, you can extend the functionality of your WebSocket server to fit your specific needs.
Event Documentation
Overview
The UranusSocketServer library provides a robust event-driven architecture, allowing you to hook into various lifecycle events of the WebSocket server. This section documents the events that are available, the context in which they are triggered, the parameters they provide, and examples of how to use them.
1. connection.opened
- Description: Dispatched when a new WebSocket connection is established.
- Context: Triggered in
WebSocketService::onOpen
. - Parameters:
ConnectionInterface $conn
: Represents the new connection.
- Example:
2. message.received
- Description: Dispatched when a WebSocket message is received.
- Context: Triggered in
WebSocketService::onMessage
. - Parameters:
ConnectionInterface $connection
: The connection instance that received the message.string $message
: The actual message content.
- Example:
3. plugin.registered
- Description: Dispatched when a plugin is registered within the system.
- Context: Triggered in
PluginManager::registerPlugins
. - Parameters:
PluginInterface $plugin
: The registered plugin instance.
- Example:
4. connection.added
- Description: Dispatched when a WebSocket connection is added to the ConnectionManager.
- Context: Triggered in
ConnectionManager::add
. - Parameters:
ConnectionInterface $conn
: The connection object that was added.
- Example:
5. connection.removed
- Description: Dispatched when a WebSocket connection is removed from the ConnectionManager.
- Context: Triggered in
ConnectionManager::remove
. - Parameters:
ConnectionInterface $conn
: The connection object that was removed.
- Example:
6. connection.subscribed
- Description: Dispatched when a connection subscribes to a specific route.
- Context: Triggered in
ConnectionManager::subscribe
. - Parameters:
ConnectionInterface $conn
: The connection that subscribed.string $route
: The route that the connection subscribed to.
- Example:
7. connection.unsubscribed
- Description: Dispatched when a connection unsubscribes from a specific route.
- Context: Triggered in
ConnectionManager::unsubscribe
. - Parameters:
ConnectionInterface $conn
: The connection that unsubscribed.string $route
: The route from which the connection unsubscribed.
- Example:
8. message.sent
- Description: Dispatched when a message is sent to all subscribers of a specific route.
- Context: Triggered in
ConnectionManager::sendToRoute
. - Parameters:
string $route
: The route to which the message was sent.string $message
: The content of the message that was sent.
- Example:
Thank you for using UranusSocketServer! We hope it helps you build your next WebSocket application with ease. If you have any questions or need support, feel free to open an issue or reach out to the community.
Happy coding!
All versions of uranus-socket-server with dependencies
cboden/ratchet Version ^0.4.3
symfony/routing Version ^5.0
php-di/php-di Version ^6.3
symfony/config Version ^5.4
symfony/yaml Version ^5.4