laravel8 swoole websocket 测试链接
时间: 2023-11-08 09:49:46 浏览: 183
首先,你需要确保已经安装了 Swoole 扩展和 Laravel Swoole 扩展,可以参考官方文档进行安装:
Swoole:https://www.swoole.com/docs/get-started/installation
Laravel Swoole:https://github.com/swooletw/laravel-swoole/blob/master/README.md
接下来,你可以创建一个 Laravel 的路由来测试 WebSocket 的链接,例如:
```php
use Swoole\Http\Request;
use Swoole\Websocket\Frame;
use Swoole\WebSocket\Server;
Route::get('/websocket', function () {
return view('websocket');
});
Route::get('/websocket/ws', function (Request $request, Server $server) {
$server->push($request->fd, "Hello, welcome to WebSocket server!");
});
Route::get('/websocket/wss', function (Request $request, Server $server) {
$server->push($request->fd, "Hello, welcome to Secure WebSocket server!");
});
```
其中,`/websocket` 是一个展示页面的路由,`/websocket/ws` 和 `/websocket/wss` 分别是 WebSocket 和 Secure WebSocket 的路由。
在 `resources/views` 目录下,你需要创建一个 `websocket.blade.php` 文件,例如:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Test</title>
</head>
<body>
<h1>WebSocket Test</h1>
<button onclick="connectWS()">Connect WebSocket</button>
<button onclick="connectWSS()">Connect Secure WebSocket</button>
<div id="output"></div>
<script>
function connectWS() {
let ws = new WebSocket('ws://127.0.0.1:9501/websocket/ws');
ws.onopen = function () {
console.log('WebSocket connected.');
document.getElementById('output').innerHTML = 'WebSocket connected.';
};
ws.onmessage = function (event) {
console.log('WebSocket received message:', event.data);
document.getElementById('output').innerHTML = 'WebSocket received message: ' + event.data;
};
}
function connectWSS() {
let ws = new WebSocket('wss://127.0.0.1:9502/websocket/wss');
ws.onopen = function () {
console.log('Secure WebSocket connected.');
document.getElementById('output').innerHTML = 'Secure WebSocket connected.';
};
ws.onmessage = function (event) {
console.log('Secure WebSocket received message:', event.data);
document.getElementById('output').innerHTML = 'Secure WebSocket received message: ' + event.data;
};
}
</script>
</body>
</html>
```
该页面中有两个按钮,分别用于连接 WebSocket 和 Secure WebSocket。当链接成功后,会在页面上显示相应的消息。
最后,你需要启动 Swoole 服务器来监听 WebSocket 和 Secure WebSocket 的请求,可以在 Laravel 项目根目录下执行如下命令:
```
php artisan swoole:http start
```
启动成功后,访问 `http://127.0.0.1:1215/websocket` 即可进入 WebSocket 测试页面。
阅读全文