|
| 1 | +<?php declare(strict_types=1); |
| 2 | +/** |
| 3 | + * Copyright © 2024 cclilshy |
| 4 | + * Email: jingnigg@gmail.com |
| 5 | + * |
| 6 | + * This software is licensed under the MIT License. |
| 7 | + * For full license details, please visit: https://opensource.org/licenses/MIT |
| 8 | + * |
| 9 | + * By using this software, you agree to the terms of the license. |
| 10 | + * Contributions, suggestions, and feedback are always welcome! |
| 11 | + */ |
| 12 | + |
| 13 | +namespace Ripple\Net; |
| 14 | + |
| 15 | +use Ripple\Net\WebSocket\Server\Server; |
| 16 | +use Ripple\Stream\Exception\ConnectionException; |
| 17 | +use Throwable; |
| 18 | +use RuntimeException; |
| 19 | + |
| 20 | +use function str_replace; |
| 21 | + |
| 22 | +class WebSocket |
| 23 | +{ |
| 24 | + /** |
| 25 | + * 创建 WebSocket 服务器 |
| 26 | + * @param string $address 监听地址, 格式:ws://host:port 或 wss://host:port |
| 27 | + * @param mixed|null $streamContext 流上下文选项 |
| 28 | + * @return Server|Throwable |
| 29 | + */ |
| 30 | + public static function server(string $address, mixed $streamContext = null): Server|Throwable |
| 31 | + { |
| 32 | + try { |
| 33 | + $httpAddress = self::convertToHttpAddress($address); |
| 34 | + return new Server($httpAddress, $streamContext); |
| 35 | + } catch (ConnectionException $e) { |
| 36 | + throw new RuntimeException($e->getMessage(), $e->getCode(), $e); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * @param string $wsAddress |
| 42 | + * @return string |
| 43 | + */ |
| 44 | + private static function convertToHttpAddress(string $wsAddress): string |
| 45 | + { |
| 46 | + $wsAddress = str_replace('ws://', 'http://', $wsAddress); |
| 47 | + $wsAddress = str_replace('wss://', 'https://', $wsAddress); |
| 48 | + return $wsAddress; |
| 49 | + } |
| 50 | +} |
0 commit comments