gpt4 book ai didi

php - 无法运行 websocket 服务器

转载 作者:行者123 更新时间:2023-12-04 16:14:18 26 4
gpt4 key购买 nike

我尝试运行我的 websocket 服务器,但由于某种我无法弄清楚的原因它无法运行。
我用过这个教程:http://socketo.me/docs/hello-world

我有这个主文件夹:
enter image description here

composer.js:

{
"autoload": {
"psr-4": {
"dealspace_websocket\\": "websocket_src"
}
},
"require": {
"cboden/ratchet": "^0.4.2"
}
}

websocket_src文件夹,只有 1 个文件, Chat.php :
<?php
namespace dealspace_websocket;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
require_once __DIR__ . "/../Model/DBConnection.php";

class Chat implements MessageComponentInterface {
protected $clients;

public function __construct() {
$this->clients = new \SplObjectStorage;
}

public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}

public function onMessage(ConnectionInterface $from, $msg) {
$JSonMsg = json_decode($msg);
if($JSonMsg['type'] === 'updownvote') {
$connection = new DBConnection();
$allowUpdate = false;
try {
$sql = 'UPDATE `deals`
SET `votes_counter` = :vc
WHERE `id` = :id';
$stmt = $connection->dbh->prepare($sql);
$allowUpdate = $stmt->execute(array(
'vc' => $JSonMsg['data']['votes'],
'id' => $JSonMsg['data']['dealid']
));
if($allowUpdate !== false) {
$dataOBJ->dealid = $JSonMsg['data']['dealid'];
$dataOBJ->votes = $JSonMsg['data']['votes'];
$returnMsg->type = 'updownvote';
$returnMsg->date = $dataOBJ;
foreach($this->clients as $client) {
$client->send(json_encode($returnMsg));
}
}
} catch(PDOException $e) {}
}
}

public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}

public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}

最后一个文件, websocket_server.php :
<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use dealspace_websocket\Chat;

require __DIR__ . '/vendor/autoload.php';

$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);

$server->run();
?>

然后,当我在主文件夹中打开 CMD 时,我运行: php websocket_server.php
这是结果:
enter image description here

这是为什么?

最佳答案

您是 require -ing vendor/autoload.php use 之后的文件- 上课。

require __DIR__ . '/vendor/autoload.php';在文件的顶部,PHP 将能够找到这些类。

<?php

require __DIR__ . '/vendor/autoload.php';

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use dealspace_websocket\Chat;

编辑

还有一个很关键的地方我一开始没注意到,就是 composer.json中的错别字。 ,您需要在命名空间指向的路径前面加上 /告诉 Composer 在给定目录下查找文件。

结果 json将是:
"psr-4": {
"dealspace_websocket\\": "websocket_src/"
}

进行此更改后运行 composer dump-autoload

You can read more about PSR-4 autoloading here and here.

关于php - 无法运行 websocket 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60026996/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com