summaryrefslogtreecommitdiffstats
path: root/vendor/textalk/websocket/examples/send.php
blob: 30e48e0c4cc470e13166f0d687f9464412cb3b32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php

/**
 * Simple send & receive client for test purpose.
 * Run in console: php examples/send.php <options> <message>
 *
 * Console options:
 *  --uri <uri> : The URI to connect to, default ws://localhost:8000
 *  --opcode <string> : Opcode to send, default 'text'
 *  --debug : Output log data (if logger is available)
 */

namespace WebSocket;

require __DIR__ . '/../vendor/autoload.php';

error_reporting(-1);

echo "> Send client\n";

// Server options specified or random
$options = array_merge([
    'uri'           => 'ws://localhost:8000',
    'opcode'        => 'text',
], getopt('', ['uri:', 'opcode:', 'debug']));
$message = array_pop($argv);

// If debug mode and logger is available
if (isset($options['debug']) && class_exists('WebSocket\EchoLog')) {
    $logger = new EchoLog();
    $options['logger'] = $logger;
    echo "> Using logger\n";
}

try {
    // Create client, send and recevie
    $client = new Client($options['uri'], $options);
    $client->send($message, $options['opcode']);
    echo "> Sent '{$message}' [opcode: {$options['opcode']}]\n";
    if (in_array($options['opcode'], ['text', 'binary'])) {
        $message = $client->receive();
        $opcode = $client->getLastOpcode();
        if (!is_null($message)) {
            echo "> Got '{$message}' [opcode: {$opcode}]\n";
        }
    }
    $client->close();
    echo "> Closing client\n";
} catch (\Throwable $e) {
    echo "ERROR: {$e->getMessage()} [{$e->getCode()}]\n";
}