-
Notifications
You must be signed in to change notification settings - Fork 255
/
echoserver.php
87 lines (77 loc) · 2.71 KB
/
echoserver.php
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
* This file is used for the tests, but can also serve as an example of a WebSocket\Server.
* Run in console: php examples/echoserver.php
*
* Console options:
* --port <int> : The port to listen to, default 8000
* --timeout <int> : Timeout in seconds, default 200 seconds
* --debug : Output log data (if logger is available)
*/
namespace WebSocket;
require __DIR__ . '/../vendor/autoload.php';
error_reporting(-1);
echo "> Echo server\n";
// Server options specified or random
$options = array_merge([
'port' => 8000,
'timeout' => 200,
'filter' => ['text', 'binary', 'ping', 'pong', 'close'],
], getopt('', ['port:', 'timeout:', 'debug']));
// 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";
}
// Initiate server.
try {
$server = new Server($options);
} catch (ConnectionException $e) {
echo "> ERROR: {$e->getMessage()}\n";
die();
}
echo "> Listening to port {$server->getPort()}\n";
// Force quit to close server
while (true) {
try {
while ($server->accept()) {
echo "> Accepted on port {$server->getPort()}\n";
while (true) {
$message = $server->receive();
$opcode = $server->getLastOpcode();
if (is_null($message)) {
echo "> Closing connection\n";
continue 2;
}
echo "> Got '{$message}' [opcode: {$opcode}]\n";
if (in_array($opcode, ['ping', 'pong'])) {
$server->send($message);
continue;
}
// Allow certain string to trigger server action
switch ($message) {
case 'exit':
echo "> Client told me to quit. Bye bye.\n";
$server->close();
echo "> Close status: {$server->getCloseStatus()}\n";
exit;
case 'headers':
$server->text(implode("\r\n", $server->getRequest()));
break;
case 'ping':
$server->ping($message);
break;
case 'auth':
$auth = $server->getHeader('Authorization');
$server->text("{$auth} - {$message}");
break;
default:
$server->text($message);
}
}
}
} catch (ConnectionException $e) {
echo "> ERROR: {$e->getMessage()}\n";
}
}