-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_server.php
More file actions
70 lines (52 loc) · 1.76 KB
/
run_server.php
File metadata and controls
70 lines (52 loc) · 1.76 KB
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
<?php
/*
* Copyright (c) 2026 Aleksandr Cherednikov
* Licensed under the MIT License. See LICENSE for details.
*/
declare(strict_types=1);
use WebSocket\Connection;
use WebSocket\MessageType;
use WebSocket\Protocol;
use WebSocket\Server;
use WebSocket\ServerOptions;
if (!extension_loaded('websocket')) {
fwrite(STDERR, "The websocket extension is not loaded.\n");
fwrite(STDERR, "Run with: php -d extension=modules/websocket.so examples/run_server.php\n");
exit(1);
}
$host = $argv[1] ?? '127.0.0.1';
$port = isset($argv[2]) ? (int) $argv[2] : 8080;
if ($port < 1 || $port > 65535) {
fwrite(STDERR, "Port must be between 1 and 65535.\n");
exit(1);
}
$server = new Server(new ServerOptions(
maxMessageSize: 1024 * 1024,
));
$server->listen($host, $port);
$server->onOpen(static function (Connection $connection): void {
echo "open {$connection->id} from {$connection->remoteAddress}\n";
$connection->send('Welcome to ext-websocket', MessageType::Text);
});
$server->onMessage(static function (Connection $connection, string $message) use ($server): void {
echo "message {$connection->id}: {$message}\n";
if ($message === 'quit') {
$connection->close(Protocol::CLOSE_NORMAL, 'bye');
return;
}
if ($message === 'shutdown') {
$connection->send('Server is stopping', MessageType::Text);
$server->stop();
return;
}
$connection->send('echo: ' . $message, MessageType::Text);
});
$server->onClose(static function (Connection $connection): void {
echo "close {$connection->id}\n";
});
$server->onError(static function (Throwable $error): void {
fwrite(STDERR, "error: {$error->getMessage()}\n");
});
echo "listening on ws://{$host}:{$port}\n";
$server->run();
echo "server stopped\n";