最近開始研究websocket
卻遇到問題不知道怎麼解決
環境
vagrant
php 7.2
swoole 4.6
fraamework 7.3
設定
WebSocketHandlerInterface.php
<?php
namespace App\Services;
use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
use Illuminate\Support\Facades\Log;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;
class WebSocketService implements WebSocketHandlerInterface
{
// 声明没有参数的构造函数
public function __construct()
{ }
public function onOpen(Server $server, Request $request)
{
Log::info('WebSocket 连接建立');
$server->push($request->fd, 'Welcome to LaravelS');
}
public function onMessage(Server $server, Frame $frame)
{
$server->push($frame->fd, $frame->data);
}
public function onClose(Server $server, $fd, $reactorId)
{
Log::info('WebSocket 连接关闭');
}
}
laravels.php
'websocket' => [
'enable' => true, // 看清楚,这里是true
'handler' => \App\Services\WebSocketService::class,
],
'swoole' => [
'dispatch_mode' => 2,
'heartbeat_idle_time' => 600,
'heartbeat_check_interval' => 60,
],
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Chat Client</title>
</head>
<body>
<div style="width:600px;margin:0 auto;border:1px solid #ccc;">
<div id="content" style="overflow-y:auto;height:300px;"></div>
<hr />
<div style="height:40px;background:white;">
<input type="text" class="form-control" id="message" placeholder="请输入内容">
<button type="button" class="btn btn-primary" onclick="sendMessage()">Primary</button>
</div>
</div>
<script type="text/javascript">
if (window.WebSocket) {
// 端口和ip地址对应不要写错
var webSocket = new WebSocket("ws://www-local.web.com.tw:5200/ws");
webSocket.onopen = function(event) {
console.log('webSocket 连接成功');
};
// 连接关闭时触发
webSocket.onclose = function(event) {
console.log("WebSocket 关闭连接");
}
//收到服务端消息回调
webSocket.onmessage = function(event) {
var content = document.getElementById('content');
content.innerHTML = content.innerHTML.concat('<p style="margin-left:20px;height:20px;line-height:20px;">' + event.data + '</p>');
console.log(event.data)
}
var sendMessage = function() {
var data = document.getElementById('message').value;
webSocket.send(data);
console.log("WebSocket 傳送訊息")
}
} else {
console.log("您的浏览器不支持WebSocket");
}
</script>
</body>
</html>
這邊我執行
當我執行HTML時
出現了
請問是我哪邊設定錯誤嗎,請大神指教
試試先在專案運行
composer dump-autoload
重新設定自動載入。
因為看起來是沒將新建的CLASS做載入。