我在 laravel 上使用 cboden/ratchet 的 websocket 包。这是地球上最令人沮丧的事情。
我什至怎么把它连接起来?
它一直向我显示此错误:在收到握手响应之前连接已关闭
// 这是我启动服务器的测试命令
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Classes\Socket\ChatSocket as Socket;
class TestCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'ratched:serve';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Just For Testing';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Socket()
)
),
8090
);
$server->run();
}
}
然后这是我的客户端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h2>Testing RATCHET</h2>
<div class="container">
<div class="content">
<div class="title">Laravel</div>
<button onclick="send()">Submit</button>
</div>
</div>
<script>
var ws = new WebSocket("ws://localhost:8090/");
ws.onopen = function () {
// Websocket is connected
console.log("Websocket connected");
ws.send("Hello World");
console.log("Message sent");
};
ws.onmessage = function (event) {
// Message received
console.log("Message received = " + event.data);
};
ws.onclose = function () {
// websocket is closed.
console.log("Connection closed");
};
</script>
</body>
</html>
//连接逻辑
<?php
namespace App\Classes\Socket;
// use App\Classes\Socket\Base\BaseSocket;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class ChatSocket implements MessageComponentInterface
{
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
我试过改变端口,没有运气
谢谢你。