@@ -35,23 +35,27 @@ info | Sent 'close' message []
3535info | Received 'close' message []
3636```
3737
38- ## A self -resuming continuous subscription Client
38+ ## Self -resuming continuous subscription Client
3939
4040This setup will create Client that sends initial message to Server,
4141and then subscribes to messages sent by Server.
4242The ` PingInterval ` (possibly change interval) will keep connection open.
4343If something goes wrong, it will in most cases be able to re-connect and resume subscription.
4444
4545``` php
46- use Psr\Http\Message\ResponseInterface;
46+ use Psr\Http\Message\{
47+ ResponseInterface,
48+ RequestInterface,
49+ };
4750use WebSocket\Client;
4851use WebSocket\Connection;
49- use WebSocket\Connection;
50- use WebSocket\Exception\Exception;
51- use WebSocket\Message\Message;
52- use WebSocket\Middleware\CloseHandler;
53- use WebSocket\Middleware\PingResponder;
54- use WebSocket\Middleware\PingInterval;
52+ use WebSocket\Exception\ExceptionInterface;
53+ use WebSocket\Message\Text;
54+ use WebSocket\Middleware\{
55+ CloseHandler,
56+ PingResponder,
57+ PingInterval,
58+ };
5559
5660// Create client
5761$client = new Client("wss://echo.websocket.org/");
@@ -61,18 +65,20 @@ $client
6165 ->addMiddleware(new PingResponder())
6266 // Add ping interval middleware as heartbeat to keep connection open
6367 ->addMiddleware(new PingInterval(interval: 30))
68+ // Timeout should have same (or lower) value as interval
69+ ->setTimeout(30)
6470 ->onHandshake(function (Client $client, Connection $connection, RequestInterface $request, ResponseInterface $response) {
6571 // Initial message, typically some authorization or configuration
6672 // This will be called everytime the client connect or reconnect
6773 $client->text($initial_message);
6874 })
69- ->onText(function (Client $client, Connection $connection, Message $message) {
75+ ->onText(function (Client $client, Connection $connection, Text $message) {
7076 // Act on incoming message
7177 $message->getContent();
7278 // Possibly respond to server
7379 $client->text($some_message);
7480 })
75- ->onError(function (Client $client, Connection|null $connection, Exception $exception) {
81+ ->onError(function (Client $client, Connection|null $connection, ExceptionInterface $exception) {
7682 // Act on exception
7783 if (!$client->isRunning()) {
7884 // Re-start if not running - will reconnect if necessary
@@ -84,23 +90,86 @@ $client
8490 ;
8591```
8692
93+ ## Server using SSL certificate capture
94+
95+ By setting ` capture_peer_cert ` the Server will capture SSL certificates.
96+ Example code set context on Server and verify the certificate during Handshake.
97+
98+ Example provided by [ marki555] ( https://github.com/marki555 ) .
99+
100+ ``` php
101+ use Psr\Http\Message\{
102+ ResponseInterface,
103+ RequestInterface,
104+ };
105+ use WebSocket\Connection;
106+ use WebSocket\Exception\CloseException;
107+ use WebSocket\Message\Text;
108+ use WebSocket\Middleware\{
109+ CloseHandler,
110+ PingResponder,
111+ };
112+ use WebSocket\Server;
113+
114+ $port = 443; // Port to use
115+ $logger = new Logger(); // PSR-3 Logger to use
116+
117+ // Create server
118+ $server = new Server(port: $port, ssl: true);
119+ $server
120+ // Set up SSL with CA certificate
121+ ->setContext(['ssl' => [
122+ 'local_cert' => 'certs/CA/acs-ws-server.crt',
123+ 'local_pk' => 'certs/CA/acs-ws-server.key',
124+ 'cafile' => 'certs/CA/ca.crt',
125+ 'verify_peer' => true, // if false, accept SSL handshake without client certificate
126+ 'verify_peer_name' => false,
127+ 'allow_self_signed' => false,
128+ 'capture_peer_cert' => true,
129+ ]])
130+ // Add standard middlewares
131+ ->addMiddleware(new CloseHandler())
132+ ->addMiddleware(new PingResponder())
133+ // Set logger
134+ ->setLogger($logger)
135+ // Resolve cerificate during Handshake
136+ ->onHandshake(function (Server $server, Connection $connection, RequestInterface $request, ResponseInterface $response) use ($logger) {
137+ $context = $connection->getContext();
138+ $certificate = $context->getOption('ssl','peer_certificate');
139+ $cn = openssl_x509_parse($certificate)['subject']['CN'];
140+ $user = myUserVerification($cn); // Verify user using yout own code
141+ if (!$user) {
142+ $logger->warning("[{$conn->getRemoteName()}] Client authentication failed, unknown CN: {$cn}");
143+ throw new CloseException(1008, Client Auth failed'); // CLOSE_POLICY_VIOLATION
144+ }
145+ $logger->info("[{$conn->getRemoteName()}] Client authenticated as '{$user}'");
146+ $connection->setMeta('user', $user); // Store for later use
147+ })
148+ ->onText(function (Server $server, Connection $connection, Text $message) use ($logger) {
149+ $logger->info("[{$conn->getMeta('user')}] Rcvd: {$message->getContent()}");
150+ })
151+ // Start listening to incoming traffic
152+ ->start()
153+ ;
154+ ```
155+
87156## The ` send ` client
88157
89- Source: [ examples/send.php] ( .. /examples/send.php)
158+ Source: [ examples/send.php] ( https://github.com/sirn-se/websocket-php/blob/v3.4-main /examples/send.php)
90159
91160A simple, single send/receive client.
92161
93162Example use:
94163``` bash
95164php examples/send.php --opcode text " A text message" # Send a text message to localhost
96165php examples/send.php --opcode ping " ping it" # Send a ping message to localhost
97- php examples/send.php --uri ws ://echo.websocket.org " A text message" # Send a text message to echo.websocket.org
166+ php examples/send.php --uri wss ://echo.websocket.org " A text message" # Send a text message to echo.websocket.org
98167php examples/send.php --opcode text --debug " A text message" # Use runtime debugging
99168```
100169
101170## The ` echoserver ` server
102171
103- Source: [ examples/echoserver.php] ( .. /examples/echoserver.php)
172+ Source: [ examples/echoserver.php] ( https://github.com/sirn-se/websocket-php/blob/v3.4-main /examples/echoserver.php)
104173
105174A simple server that responds to received commands.
106175
@@ -125,20 +194,20 @@ These strings can be sent as message to trigger server to perform actions;
125194
126195## The ` random ` client
127196
128- Source: [ examples/random_client.php] ( .. /examples/random_client.php)
197+ Source: [ examples/random_client.php] ( https://github.com/sirn-se/websocket-php/blob/v3.4-main /examples/random_client.php)
129198
130199The random client will use random options and continuously send/receive random messages.
131200
132201Example use:
133202``` bash
134- php examples/random_client.php --uri ws ://echo.websocket.org # Connect to echo.websocket.org
203+ php examples/random_client.php --uri wss ://echo.websocket.org # Connect to echo.websocket.org
135204php examples/random_client.php --timeout 5 --framesize 16 # Specify settings
136205php examples/random_client.php --debug # Use runtime debugging
137206```
138207
139208## The ` random ` server
140209
141- Source: [ examples/random_server.php] ( .. /examples/random_server.php)
210+ Source: [ examples/random_server.php] ( https://github.com/sirn-se/websocket-php/blob/v3.4-main /examples/random_server.php)
142211
143212The random server will use random options and continuously send/receive random messages.
144213
@@ -151,7 +220,7 @@ php examples/random_server.php --debug # Use runtime debugging
151220
152221## The ` delegating ` server
153222
154- Source: [ examples/delegating_server.php] ( .. /examples/delegating_server.php)
223+ Source: [ examples/delegating_server.php] ( https://github.com/sirn-se/websocket-php/blob/v3.4-main /examples/delegating_server.php)
155224
156225By using context switching, the server will act as a proxy and forward incoming messages to a remote server.
157226Please note that switching between listening context can appear slow.
0 commit comments